Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Build Python binding of C++ library with cffi (PyPy/Py3K compatible)

Run with Python:

pip-2.7 install cffi
PYTHON=python2.7 sh go.sh

Run with PyPy:

pip-pypy install cffi
PYTHON=pypy sh go.sh

Run with Py3K:

pip-3.3 install cffi
PYTHON=python3.3 sh go.sh

The expected output:

=> now run the native one
hello, world
=> now run the pypy bound one
hello, cffi
#!/usr/bin/env sh
set -e
[ -z "$PYTHON" ] && PYTHON="python"
g++ -o ./hello ./libhello.cpp
echo "=> now run the native one"
./hello
g++ -o ./libhello.so ./libhello.cpp -fPIC -shared
echo "=> now run the $PYTHON bound one"
python hello.py
import cffi
ffi = cffi.FFI()
ffi.cdef("void cffi_hello(char *name);")
C = ffi.dlopen("./libhello.so")
def hello(name):
C.cffi_hello(name)
if __name__ == "__main__":
hello("cffi")
#include <iostream>
class User
{
std::string name;
public:
User(char *name):name(name) {}
User(std::string &name):name(name) {}
std::string greet() { return "hello, " + name; }
};
void hello(char *name)
{
User user(name);
std::cout << user.greet() << std::endl;
}
int main()
{
hello((char *) "world");
return 0;
}
extern "C"
{
extern void cffi_hello(char *name)
{
return hello(name);
}
}
@0xnurl

This comment has been minimized.

Copy link

0xnurl commented Mar 2, 2017

This is extremely helpful. Thanks!

@jakab922

This comment has been minimized.

Copy link

jakab922 commented May 15, 2017

Thanks! Really useful indeed.

@yunqu

This comment has been minimized.

Copy link

yunqu commented Oct 26, 2018

Like it

@danielmdPhantom

This comment has been minimized.

Copy link

danielmdPhantom commented Jul 24, 2019

very helpful. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.