Skip to content

Instantly share code, notes, and snippets.

@likebeta likebeta/README.rst forked from tonyseek/README.rst
Created Dec 8, 2016

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

Run with PyPy:

pip-pypy install cffi
PYTHON=pypy sh

Run with Py3K:

pip-3.3 install cffi
PYTHON=python3.3 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"
g++ -o ./ ./libhello.cpp -fPIC -shared
echo "=> now run the $PYTHON bound one"
import cffi
ffi = cffi.FFI()
ffi.cdef("void cffi_hello(char *name);")
C = ffi.dlopen("./")
def hello(name):
if __name__ == "__main__":
#include <iostream>
class User
std::string name;
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
You can’t perform that action at this time.