Skip to content

Instantly share code, notes, and snippets.

@lagagain
Created August 26, 2018 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagagain/63c38cb960285d5dc06268a8c129b1ac to your computer and use it in GitHub Desktop.
Save lagagain/63c38cb960285d5dc06268a8c129b1ac to your computer and use it in GitHub Desktop.
[pratice] Python3.5 call C++ function with extern "C"
#include "hello.h"
#include<Python.h>
using namespace std;
extern "C"{
static PyObject *_hello(PyObject *self, PyObject *args){
hello();
return self;
}
static PyMethodDef HelloMethods[] = {
{"hello", _hello, METH_VARARGS,""},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef hellomodule = {
PyModuleDef_HEAD_INIT,
"hello", /* name of module */
NULL, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
HelloMethods
};
PyMODINIT_FUNC PyInit_hello(void){
return PyModule_Create(&hellomodule);
}
}
void hello(){
cout<<"Hello"<<endl;
return ;
}
#include<Python.h>
#include<iostream>
#include<cstdlib>
void hello();
import hello
hello.hello()
print("END")
#include<iostream>
#include<cstdlib>
#include "./hello.h"
using namespace std;
int main(){
hello();
}
CPP = c++
C = gcc
DELETE = rm -f
all:
${CPP} -fPIC -shared hello.cpp -o hello.so -I/usr/include/python3.5/ -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/ -lpython3.5
exec_hello:
${CPP} main.cpp hello.cpp -o hello -I/usr/include/python3.5/ -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu/ -lpython3.5
clean:
${DELETE} hello hello.so
@lagagain
Copy link
Author

use make to build hello.so, then exec python3 hello.py

or use make exec_hello to build exec file, it test c++ code is right.

finally, use make clean to delete .so file and exec file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment