bestu 发表于 2015-4-20 11:39:53

Python调用C/C++的种种方法

  Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子,所有例子都在ubuntu9.10, python2.6下试过.
  1. Python 调用 C (base)
  想在python中调用c函数, 如这儿的fact
  #include
int fact(int n)
{
if (n > import hello
>>> hello.greet()
'hello, world'
  
  4. python 调用 c++ (ctypes)
  ctypes is anadvanced ffi (Foreign Function Interface) package for Python 2.3 and higher. In Python 2.5 it is already included.
  ctypes allows to call functions in dlls/shared libraries and has extensivefacilities to create, access and manipulate simple and complicated C data typesin Python - in other words: wrap libraries in pure Python. It is even possibleto implement C callback functions in pure Python.
  http://python.net/crew/theller/ctypes/
  #include
class TestFact{
    public:
   TestFact(){};
    ~TestFact(){};
    int fact(int n);
};
intTestFact::fact(int n)
{
if (n >> import ctypes
>>> pdll =ctypes.CDLL('/home/ubuntu/tmp/example.so')
>>>pdll.fact(4)
12



http://img.zemanta.com/pixy.gif?x-id=40be308d-5a32-8d9f-9031-2ff9936b9eb3
页: [1]
查看完整版本: Python调用C/C++的种种方法