Skip to content

Instantly share code, notes, and snippets.

@lagagain

lagagain/hello.cpp

Created Aug 26, 2018
Embed
What would you like to do?
[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

This comment has been minimized.

Copy link
Owner Author

@lagagain lagagain commented Aug 26, 2018

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
You can’t perform that action at this time.