Skip to content

Instantly share code, notes, and snippets.

@theonewolf
Last active December 20, 2015 21:59
Show Gist options
  • Select an option

  • Save theonewolf/6201506 to your computer and use it in GitHub Desktop.

Select an option

Save theonewolf/6201506 to your computer and use it in GitHub Desktop.
skeleton Python C++ interface
#include <Python.h>
#include <string.h>
#include "hello_world.h"
static PyObject *
hello_func(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
return NULL;
hello_world(str);
return Py_BuildValue("i", strlen(str));
}
static PyMethodDef helloMethods[] = {
{"func", hello_func, METH_VARARGS, "Prints a string."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inithello(void)
{
PyObject *m;
m = Py_InitModule("hello", helloMethods);
if (m == NULL)
return;
}
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
void hello_world(const char* c_string)
{
cout << string(c_string) << endl;
}
#ifdef __cplusplus
}
#endif
#ifndef __HELLO_WORLD
#define __HELLO_WORLD
void hello_world(const char* c_string);
#endif
default:
python setup.py build
ln -fs build/lib.linux-x86_64-2.7/hello.so hello.so
python -c 'import hello; hello.func("it is workingses!")'
test_hello:
g++ test_main.cpp \
hello_world.cpp \
-o test_main
clean:
rm -rf hello.so build test_main
#!/usr/bin/env python
from distutils.core import setup, Extension
module = Extension('hello',
sources = ['hello.c', 'hello_world.cpp'])
setup (name = 'Hello',
version = '1.0',
description = 'This is a demo package.',
ext_modules = [module])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment