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
- Python 使用ctypes调用 C 函数
- Python调用ctypes使用C函数printf
- Python 使用ctypes调用 C 函数
- Python 使用ctypes调用C/C++
- python使用ctypes调用C/C++
- ctypes: 使用python调用C编写的动态链接库
- 【转】Python调用ctypes使用C函数printf
- Python使用ctypes调用C函数传参处理
- python学习笔记--使用ctypes调用C函数
- Python 使用库ctypes调用C代码接口
- python ctypes - python调用C语言库
- Python:使用ctypes库调用外部DLL(附带ctypes c 类型转换图)
- 【Python】Python通过ctypes调用C动态链接库
- python脚本利用ctypes调用c模块返回字符串
- C/C++ 生成的.so文件,python 用ctypes调用
- python使用 C语言类型、ctypes 的用法
- Python与C之间的相互调用(Python C API及Python ctypes库)
- Python与C之间的相互调用(Python C API及Python ctypes库)【转】
- 3.2 虚拟内存管理
- 数据库连接池浅析
- leetcode-Intersection of Two Arrays-349
- oracle11g 拆分字符串的详细技巧
- 如何删除计算机中的服务
- Python 使用ctypes调用C/C++
- PAT乙级.1016. 部分A+B (15)
- Java面试参考指南——同步
- merge into 插入或更新数据
- #Android#集合与异常处理
- 剑指offer——对称的二叉树判断
- A Neural Probabilistic Language Model
- Android .gitignore
- 线程池