Python 代码到 C++ lib 或 DLL
python code to c++ lib or dll
我有一些 python 代码想从 C++ 使用,我想用 lib 或 dll 构建它? 我该怎么做?代码具有依赖项:
import socket
import string
import struct
import sys
也许是太平船务
您可以使用 cython 并编写精简包装器将其导出为 C
Cython lib helloWorld.pyx
:
import sys
sys.path.append(".") #yourlib is in current folder
import yourlib #you can import any python module
cdef public void helloWorld():
print "Hello World Cython!"
yourlib.helloWorld("Python")
cdef public int my_sum(int x, int y):
return x*x+y
from libcpp.string cimport string
cdef public string testString( string sx, string sy ):
x = int(sx.c_str())
y = int(sy.c_str())
ret= "%d*%d+%d=%d"%(x,x,y,my_sum(x,y))
cdef char* ret2= ret
return string( ret2 )
使用 cython 编译 (创建 helloWorld.cpp
, helloWorld.h
):
cython --cplus helloWorld.pyx
您的代码program.cpp
:
#include <string>
#include <iostream>
#include "Python.h"
#include "helloWorld.h" // it's cpp header so remove __PYX_EXTERN_C (bug)
int main(int argc, char *argv[]) {
Py_Initialize(); //start python interpreter
inithelloWorld(); //run module helloWorld
helloWorld();
std::cout << testString("6","6") << std::endl; #it's fast!
Py_Finalize();
return 0;
}
编译并运行:
g++ program.cpp helloWorld.cpp -I/usr/include/python2.7/ -lpython2.7
./a.out
Hello World Cython!
Hello World Python!
6*6+6=42
另一种方法是使用 boost::p ython
您的代码program.cpp
:
#include <string>
#include <iostream>
#include <boost/python.hpp>
int main(int argc, char *argv[]) {
Py_Initialize();
boost::python::object sys = boost::python::import("sys");
sys.attr("path").attr("append")(".");
boost::python::object main_module = boost::python::import("yourlib");
main_module.attr("helloWorld")("boost_python");
boost::python::object ret= main_module.attr( "my_sum" )( 10, 10 );
std::cout << boost::python::extract<char const*>(ret) << std::endl;
Py_Finalize();
return 0;
}
编译并运行:
g++ program.cpp -I/usr/include/python2.7/ -lpython2.7 -lpython_boost
./a.out
Hello World boost_python!
10*10+10=110
你可能想检查如何在另一个应用程序中嵌入python(http://docs.python.org/extending/embedding.html)。
相关文章:
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- 解析引用 |exe/dll vs lib
- CMake 生成的 MSVC 项目找不到符号,即使为其相关 dll 正确生成了 lib 文件也是如此
- 从 .lib 文件创建一个.dll文件
- 可执行文件C++包括.obj,.lib和.dll吗?
- 无法在 DLL 中链接 SDL2-static.lib
- 链接器找不到导入的 DLL 的 LIB 文件
- C++:重命名dll和lib并链接
- C++ CLR dll 需要 .lib 文件,但非 CLR 不需要
- 如何找出依赖于LIB文件的DLL列表?
- 链接 .lib 并在 Windows 中使用 .dll 在 C++ 在 Eclipse 中
- 将标头和 lib 转换为 dll 以将其与 c# 一起使用
- 为什么我的程序寻找共享资源.dll而不是Commons.lib
- 从.dll中调用.lib in C
- GHCi 无法在 Windows 上加载.dll lib(C++ lib)
- 如果在 DLL/Lib 中定义了对象,是否可以在客户端中实例化对象?
- "/MD /MT"和"dll lib"之间的概念歧义
- 在dll/lib上创建链接
- 如何检查 dll/lib 中的函数是否在 windows 中"C"?