Skip to content

Instantly share code, notes, and snippets.

@boozook
Forked from tonyseek/README.rst
Created June 10, 2017 19:10
Show Gist options
  • Save boozook/ca58244c32ba9d59315c45152c0f0f95 to your computer and use it in GitHub Desktop.
Save boozook/ca58244c32ba9d59315c45152c0f0f95 to your computer and use it in GitHub Desktop.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment