Python与C++交互

1、C++调用python,并且获取返回值

#include "stdafx.h"
#include <Python.h>
#include <Windows.h>

void test()
{
    PyRun_SimpleString("x = 10" );
    PyRun_SimpleString("y = 20" );
    PyObject* mainModule = PyImport_ImportModule("__main__" );
    PyObject* dict = PyModule_GetDict(mainModule);
    PyObject* px = PyDict_GetItemString(dict, "x");
    if (px)
    {
        long  x = PyLong_AsLong(px);
        printf("result = %d\r\n" , x);
        Py_DECREF(px);
    }

    PyObject* resultObject = PyRun_String("x + y" , Py_eval_input, dict, dict);
    if (resultObject)
    {
        long  result = PyLong_AsLong(resultObject);
        printf("result = %d\r\n" , result);
        Py_DECREF(resultObject);
    }


}

int _tmain(int argc, _TCHAR* argv[])
{	
	// 如果出现ImportError: No module named site,必须设置一下
	Py_SetPythonHome("F:\\Python27");
	Py_Initialize();//初始化python	
	test();
	PyRun_SimpleString("print 'hello python'\nprint 'ABC'");//直接运行python代码
	Py_Finalize(); //释放python
	return 0;
}


2、python调用C++

新建一DLL工程,生成文件设置成hello.pyd,工程代码如下

#include "stdafx.h"
#include <Python.h>
#include <string.h>

#define PYC_API _declspec(dllexport)

static PyObject *message(PyObject *self, PyObject *args)
{
	char *szFromPy;
	char szResult[100];
	ZeroMemory(szResult, sizeof(szResult));
	if (!PyArg_Parse(args, "(s)", &szFromPy))
	{
		return NULL;
	}
	else 
	{
		sprintf(szResult, "Hello %s", szFromPy);
		MessageBoxA(NULL, szResult, "Python Call C", MB_OK);
		return Py_BuildValue("s", szResult);
	}
}

static struct PyMethodDef hello_methods[] = 
{
	{"message", message, 1},
	{NULL, NULL}
};


#ifdef __cplusplus
extern "C" {
#endif

PYC_API void inithello() 
{
	(void)Py_InitModule("hello", hello_methods);
}

#ifdef __cplusplus
}
#endif

编译生成hello.pyd文件之后,在同一目录下新建一个test.py测试文件,内容如下

# -*- coding: utf-8-*-
import hello

s = hello.message("World!哈哈")
print s

双击运行就可以看见结果了,欧耶,就是这么简单。


猜你喜欢

转载自blog.csdn.net/haart/article/details/51567620
今日推荐