python代码到c ++ lib或dll

时间:2012-04-26 11:20:23

标签: c++ python dll

我有一些我想在C ++中使用的python代码,我想在lib或dll中构建它?我该怎么做? 代码有依赖关系:

import socket
import string
import struct
import sys

也许是PIL

2 个答案:

答案 0 :(得分:5)

您可以使用cython并编写thin wrapper to export it to 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::python

您的代码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

答案 1 :(得分:3)

您可能想要检查如何在另一个应用程序中嵌入python(http://docs.python.org/extending/embedding.html)。