Just a few months ago, the C + + function inside the first load Python script, and then call the inside of the DEF function, I put the code, you in the main function, call the Getdatabyscript function, and the same directory of a fucktest.py, I'm centos6.7.
Compile
g++-O test test.cpp-lpython2.7
CallPython.h
#include <Python.h>
#include <string>
using namespace Std;
char* getdatabyscript (const char* modulename,int& buffersize,int& errinfo)
{
Errinfo = 0;
buffersize = 0;
Py_initialize ();
if (! Py_isinitialized ())
{
Errinfo = 1;
return NULL;
}
pyrun_simplestring ("Import sys");
Pyrun_simplestring ("Sys.path.insert (0, './')");
Pyrun_simplestring ("Print Sys.path");
pyobject* pName = pystring_fromstring (modulename);
pyobject* pmodule = Pyimport_import (pName);
if (!pmodule)
{
printf ("Can ' t import error\n");
Errinfo = 2;
return NULL;
}
pyobject* pdict = pymodule_getdict (pmodule);
if (!pdict)
{
Errinfo = 3;
return NULL;
}
pyobject* PFunc = pydict_getitemstring (pdict, "Callfuncnoargs");
if (!pfunc | |!) Pycallable_check (PFunc))
{
Errinfo = 4;
return NULL;
}
pyobject* PArgs = pytuple_new (2);
Pytuple_setitem (Pargs,0,py_buildvalue ("L", 100));
Pytuple_setitem (Pargs,1,py_buildvalue ("L", 200));
pyobject* res = Pyobject_callobject (pfunc,null);
if (! Pystring_check (RES))
{
Errinfo = 5;
return NULL;
}
Else
{
buffersize = Int (pystring_size (res));
Return (char*) pystring_asstring (res);
}
}
Test.cpp
#include <iostream>
#include "CallPython.h"
using namespace Std;
int main ()
{
int size = 0;
int errinfo = 0;
Getdatabyscript ("Fucktest", size,errinfo);
return 0;
}
fucktest.py
Def Callfuncnoargs ():
Print "test.py func called!!!"
return "Fuck"
C language calls Python script function