python调用C++
一。利用Ctypes
2014-04-29
EXAMPLE:
//VS2012,新建WINDOWS Project ,下一步,选择dll
// test.h #include<iostream> extern "C" int __declspec(dllexport)add(int x,int y); // .cpp #include "test.h" int __declspec(dllexport)add(int x,int y) { //std::cout<<x<<" "<<y<<std::endl; std::cout<<x+y<<std::endl; return x+y; }
编译平台为X64(因为我的python为64位)
import ctypes ll=ctypes.cdll.LoadLibrary lib=ll(r"D:\VSProjects\pyc1\x64\Debug\pyc1.dll") lib.add(1,3)
调用成功
问题注意:
1.python为64位,必须导入64位的dll,否则会发生win32错误
2.路径在windows下为D:\\。。。等等
二。利用Python C API
生成C++ dll 代码
注意:因为我的python是安装包安装的,64,没有源码,只提供了include 和Release下的lib。所以编程平台必须为X64 Release
debug会发生找不到python27_d.lib的错误
#include "Python.h"
static PyObject *ex_foo(PyObject *self, PyObject *args)
{
printf("Hello, world/n");
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef example_methods[] =
{
{"foo", ex_foo, METH_VARARGS, "foo() doc string"},
{NULL, NULL}
};
PyMODINIT_FUNC
initexample(void)
{
Py_InitModule("example", example_methods);
}
static PyObject *ex_foo(PyObject *self, PyObject *args) { printf("Hello, world/n"); Py_INCREF(Py_None); return Py_None; } static PyMethodDef example_methods[] = { {"foo", ex_foo, METH_VARARGS, "foo() doc string"}, {NULL, NULL} }; PyMODINIT_FUNC initexample(void) { Py_InitModule("example", example_methods); }
最后,将生成的dll改为.pyd后缀
文件结构大概长这样
test.py 代码:
import os dllpath=".\\" if dllpath not in os.sys.path: os.sys.path.append(dllpath) print os.sys.path import example example.foo()
['D:\\VSProjects\\PyCAPI\\x64\\Release', 'D:\\Program Files\\Python27\\lib\\site -packages\\setuptools-3.4.1-py2.7.egg', 'D:\\Program Files\\Python27\\lib\\site- packages\\gnumpy-0.2-py2.7.egg', 'C:\\Windows\\system32\\python27.zip', 'D:\\Pro gram Files\\Python27\\DLLs', 'D:\\Program Files\\Python27\\lib', 'D:\\Program Fi les\\Python27\\lib\\plat-win', 'D:\\Program Files\\Python27\\lib\\lib-tk', 'D:\\ Program Files\\Python27', 'D:\\Program Files\\Python27\\lib\\site-packages', 'D: \\Program Files\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode', '.\\']
Hello, world/n 请按任意键继续. . .
参考资料:
http://blog.csdn.net/vagrxie/article/details/3779247
http://blog.csdn.net/vagrxie/article/details/5251306