Python 代码到 C++ lib 或 DLL

python code to c++ lib or dll

本文关键字:DLL lib C++ 代码 Python      更新时间:2023-10-16

我有一些 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.cpphelloWorld.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)。