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

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


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值