C language calls Python script function

Source: Internet
Author: User
Tags python script

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.