使用ctype在python中调用c

之前在python中调用c++是通过命令行调用的,参数传递是使用文件IO的形式,所以会特别慢

现在用ctypes,参数传递传的只是内存中的指针,这就很舒服

现在来总结下如何使用cytpes在python中调用c (Ubuntu系统下)

首先写一个test.c的源码

int add(int a, int b)
{
    return a + b;
}

然后编译成.so文件 命令如下

gcc -fPIC -c test.c

gcc -shared -o test.so test.o

执行完这两个命令之后就出现了test.so文件

现在我们就能在python中调用这个动态链接库了

python代码如下

import ctypes as c

libc = c.cdll.LoadLibrary(‘/home/zhaodao/ffb_workspace/ctypes学习/test.so‘)

ans = libc.add(10, 2)
print(ans)

原文地址:https://www.cnblogs.com/shensobaolibin/p/9900661.html

时间: 2024-07-31 21:19:18

使用ctype在python中调用c的相关文章

[Python-MATLAB] 在Python中调用MATLAB的API

可以参考官方的说明文档: http://cn.mathworks.com/help/matlab/matlab_external/get-started-with-matlab-engine-for-python.html MATLAB Engine API的使用文档: http://cn.mathworks.com/help/matlab/matlab-engine-for-python.html 原材料: 1.MATLAB 2015a  32位的 2.Python 2.7.13    32位

Python脚本传参和Python中调用mysqldump

Python脚本传参和Python中调用mysqldump<pre name="code" class="python">#coding=utf-8 import MySQLdb import sys import os # 李红颖编写,用户湖南CLV数据分割使用 print 'dump database:',sys.argv[1] ##传入的第一个参数,数据库名称 print 'dump table:',sys.argv[2] ##传入的第二个参数,表

python 中调用windows系统api操作剪贴版

# -*- coding: utf-8 -*- ''' Created on 2013-11-26 @author: Chengshaoling ''' import win32clipboard as w32 import win32con class OperateClipboard(object): def __init__(self): # print "OperateClipboard" pass def getText(self): w32.OpenClipboard()

在Python中调用C++模块

首先,这是自我转载:YellowTree | STbioinf的文章「在Python中调用C++模块」 在Python中成功实现了对原来C++代码模块的复用!这个好处多多,Python写得快,C++跑得快,那就是既快又快了!方法很简单,以至于我能够用一张截图记录下整个过程(点击图片看大图)! 其实,注意到,必须在原来的C++代码后面添加extern “C”来辅助(C则不需要,这也是与复用C代码时最大的不同点),不然Python在调用这个构建后的动态链接库时是找不到原来的方法或者函数的,说到底还都

使用ctypes在Python中调用C++动态库

使用ctypes在Python中调用C++动态库 入门操作 使用ctypes库可以直接调用C语言编写的动态库,而如果是调用C++编写的动态库,需要使用extern关键字对动态库的函数进行声明: #include <iostream> using namespace std; extern "C" { void greet() { cout << "hello python" << endl; } } 将上述的C++程序编译成动态链

socket实现在python中调用操作系统的命令(subprocess)

在python中调用操作系统的命令 import os import subprocess # r = os.popen('ipconfig') r = subprocess.Popen('ls',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE). # subprocess.Popen(cmd,shell=True,subprocess.stdout,subprocess.stderr) # cmd : 代表系统命令 # shel

Python中调用其他程序的方式

前言 在Python中,可以方便地使用os模块来运行其他脚本或者程序,这样就可以在脚本中直接使用其他脚本或程序提供的功能,而不必再次编写实现该功能的代码.为了更好地控制运行的进程, 可以使用win32process模块中的函数,如果想进一步控制进程,则可以使用ctype模块,直接调用kernel32.dll中的函数.下面介绍4种方式: 1.os.system()函数 os模块中的system()函数可以方便地运行其他程序或者脚本,模式如下: os.system(command):command:

Python中调用c语言

Python中有时需要调用c程序中的函数.使用ctype库可以很方便地调用c语言.现说明方法,以及注意事项. c程序编译为.so文件: 我们需要的c语言文件为test.c,要从其中调用func(x,y)函数. gcc -fPIC -shared test.c -o test.so 导入该文件 随后,我们在python中导入该test.so文件,方法如下: import os from ctypes import * p = os.getcwd() + '/test.so' # 文件路径 f =

python中调用C++写的动态库

一.环境:Windows XP + Python3.2 1. dll对应的源文件(m.cpp): #include <stdio.h> extern "C" { _declspec(dllexport) int add(int a, int b) { return a+b; } _declspec(dllexport) void print_sum(unsigned long ulNum) { while(ulNum != 0) { printf("The ulN