1.环境:
win10、VS2017、Anaconda3(python3.x)
2.步骤:
2.1.在vs2017新建一个空文件testpy3,新建文件test.c
和math_test.py
//test.c
#include <Python.h>
int main(int argc, char *argv[])
{
//设定参数值
int a=3;
int b=6;
//初始化
Py_SetProgramName(argv[0]);
Py_Initialize();
//测试python3的打印语句
PyRun_SimpleString("print('Hello Python!')\n");
//执行import语句,把当前路径加入路径中,为了找到math_test.py
PyRun_SimpleString("import os,sys");
PyRun_SimpleString("sys.path.append('./')");
//测试打印当前路径
PyRun_SimpleString("print(os.getcwd())");
PyObject *pModule;
PyObject *pFunction;
PyObject *pArgs;
PyObject *pRetValue;
//import math_test
pModule = PyImport_ImportModule("math_test");
if(!pModule){
printf("import python failed!!\n");
return -1;
}
//对应math_test.py中的def add_func(a,b)函数
pFunction = PyObject_GetAttrString(pModule, "add_func");
if(!pFunction){
printf("get python function failed!!!\n");
return -1;
}
//新建python中的tuple对象
pArgs = PyTuple_New(2);
PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", a));
PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", b));
//调用函数
pRetValue = PyObject_CallObject(pFunction, pArgs);
//python3中只有long,PyLong_AsLong(python2中是PyInt_AsLong)
printf("%d + %d = %ld\n",a,b,PyLong_AsLong(pRetValue));
Py_DECREF(pModule);
Py_DECREF(pFunction);
Py_DECREF(pArgs);
Py_DECREF(pRetValue);
if(!pModule){
printf("import python failed!!\n");
return -1;
}
Py_Finalize();
//方便查看
while(1);
return 0;
}
//math_test.py
def add_func(a,b):
return a+b
def sub_func(a,b):
return (a-b)
3.编译
cl test.c -I C:\APP\Anaconda3\include C:\APP\Anaconda3\libs\python36.lib
4.编译后得到test.exe文件
运行得到