说明:测试环境为ubuntu18.04,使用语言Python3,C++. 由于python中无法定义(short)类型,或者(int)类型,所以使用Python调用C++的方法,在C++中计算,然后用Python调用.
C++调用Python
Python模块代码:
#!/usr/bin/python
#Filename:TestModule.py
def Hello(s):
print "Hello World"
print s
def Add(a, b):
print 'a=', a
print 'b=', b
return a + b
class Test:
def __init__(self):
print "Init"
def SayHello(self, name):
print "Hello,", name
return name
C++代码:
#include<iostream>
#include<Python.h>
using namespace std;
int main(int argc, char* argv[])
{
//初始化python
Py_Initialize();
//直接运行python代码
PyRun_SimpleString("print 'Python Start'");
//引入当前路径,否则下面模块不能正常导入
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
//引入模块
PyObject *pModule = PyImport_ImportModule("TestModule");
//获取模块字典属性
PyObject *pDict = PyModule_GetDict(pModule);
//直接获取模块中的函数
PyObject *pFunc = PyObject_GetAttrString(pModule, "Hello");
//参数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型,元组中的python类型查看python文档
PyObject *pArg = Py_BuildValue("(s)", "Hello Charity");
//调用直接获得的函数,并传递参数
PyEval_CallObject(pFunc, pArg);
//从字典属性中获取函数
pFunc = PyDict_GetItemString(pDict, "Add");
//参数类型转换,传递两个整型参数
pArg = Py_BuildValue("(i, i)", 1, 2);
//调用函数,并得到python类型的返回值
PyObject *result = PyEval_CallObject(pFunc, pArg);
//c用来保存c/c++类型的返回值
int c;
//将python类型的返回值转换为c/c++类型
PyArg_Parse(result, "i", &c);
//输出返回值
printf("a+b=%d\n", c);
//通过字典属性获取模块中的类
PyObject *pClass = PyDict_GetItemString(pDict, "Test");
//实例化获取的类
PyObject *pInstance = PyInstance_New(pClass, NULL, NULL);
//调用类的方法
result = PyObject_CallMethod(pInstance, "SayHello", "(s)", "Charity");
//输出返回值
char* name=NULL;
PyArg_Parse(result, "s", &name);
printf("%s\n", name);
PyRun_SimpleString("print 'Python End'");
//释放python
Py_Finalize();
getchar();
return 0;
}
编译:
g++ -I/usr/include/python2.7 PythonWithCpp.cpp -lpython2.7
Python调用C++
C++代码:
#include<iostream>
// //用C++必须在函数前加extern "C"
// extern "C" int Add(int a,int b)
// {
// return a+b;
// }
//用C++必须在函数前加extern "C"
extern "C" int data_type(int a,int b)
{
return (short)((a << 8)| b);
}
编译:
g++ -c -fPIC LibPythonTest.cpp
g++ -shared LibPythonTest.o -o LibPythonTest.so
Python代码:
#!/bin/python3
#Filename:PythonCallCpp.py
from ctypes import *
import os
# libPythonTest = cdll.LoadLibrary('./LibPythonTest.so')
# print(libPythonTest.Add(1,1))
libPythonTest = cdll.LoadLibrary('./LibPythonTest.so')
print(libPythonTest.data_type(0xFD,0x78))
运行:
python3 PythonCallCpp.py
运行结果:
-648