Python 使用ctypes调用C/C++

来源:互联网 发布:程序员必读书籍 编辑:程序博客网 时间:2024/05/16 23:51

一、Python调用C语言

1、C语言文件:ctest.c

#include <stdlib.h>  int fun(int x, int y)  {      printf("Your input %i and %i\n", a, b);      return a + b;  }  

2、动态库 gcc编译:gcc -o libctest.so -shared -fPIC ctest.c

3、 Python调用动态库的文件:demo.py

# coding: utf-8from types import *# 此处是调用动态库lib = cdll.LoadLibrary ("./libctest.so")print lib.foo(1, 7)  

4、运行结果

> > > python test.py
> > > 8 #这是print输出的结果

二、Python调用C++语言

因为ctypes只能调用C函数,不能直接调用方法,但是可以通过extern “C”来解析C++方法。

有两种方法来实现调用C++语言。

1. 定义C++方法前加 extern “C”

#include <iostream>using namespace std;extern "C" int fun(int x, int y)  {      printf("Your input %i and %i\n", a, b);      return a + b;  }  

2. 在定义C++方法后构建新的 extern “C”方法

#include <iostream>using namespace std;int fun(int x, int y)  {      printf("Your input %i and %i\n", a, b);      return a + b;  }  extern "C"{    int fun2(int x, int y)//注意,此处是fun2(),这是一个新的方法,Python通过调用这个方法来完成对C++方法的调用    {        fun(x, y);    }}

Python调用C++语言的编译和运行和C语言相同,可以参考第一部分。

0 0
原创粉丝点击