python importlib 生成so文件 报错_『Python CoolBook』ctype读取Linux动态库so文件

一、动态库文件生成

源文件hello.c

#include "hello.h"

#include

void hello(const char *name)

{

printf("Hello %s!\n", name);

}

int factorial(int n)

{

if (n < 2)

return 1;

return factorial(n - 1) * n;

}

/* Compute the greatest common divisor */

int gcd(int x, int y) {

int g = y;

while (x > 0) {

g = x;

x = y % x;

y = g;

}

return g;

}

头文件hello.h

#ifndef _HELLO_H_

#define _HELLO_H_

#ifdef __cplusplus

extern "C" {

#endif

void hello(const char *);

int factorial(int n);

int gcd(int x, int y);

#ifdef __cplusplus

}

#endif

#endif

结构体如果放在.h文件中和放在.c中写法没有区别,且重复定义会报错。

如果使用了c++特性(.c文件需要是.cpp文件),.h头需要对应声明,如下结构会更保险,

#ifndef __SAMPLE_H__

#define __SAMPLE_H__

#ifdef __cplusplus

extern "C" {

#endif

/* 声明主体 */

#ifdef __cplusplus

}

#endif

#endif

编译so动态库

gcc -shared -fPIC -o libhello.so hello.c

此时可以看到so文件于文件夹下。

二、使用python调用c函数

尝试使用ctypes模块载入库,并调用函数,

from ctypes import cdll

libhello= cdll.LoadLibrary("./libhello.so")

libhello.hello(‘You‘)

res1 = libhello.factorial(100)

res2 = libhello.gcd(100, 2)

print(libhello.avg)

print(res1, res2)

>>> python hello.py

Hello Y!

0 2

函数hello和我们预想的不一致,仅仅输出了首字母"Y",对于cookbook的其他c函数实际上我也做了导入,但是数据格式c和python是需要转换的,调用起来不是很容易的一件事,本篇重点在于成功导入python,之后的问题之后讲。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值