Skip to content

Instantly share code, notes, and snippets.

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);

This comment has been minimized.

Copy link

0xnurl commented Mar 2, 2017

This is extremely helpful. Thanks!


This comment has been minimized.

Copy link

jakab922 commented May 15, 2017

Thanks! Really useful indeed.


This comment has been minimized.

Copy link

yunqu commented Oct 26, 2018

Like it


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.