首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >[linux][原创]C++ so库的编译python调用

[linux][原创]C++ so库的编译python调用

作者头像
git clone firc-dataset
发布2025-07-18 13:33:34
发布2025-07-18 13:33:34
3430
举报

test.h

#pragma once #include <stdio.h> extern "C" int Add(int a, int b); extern "C" int Max(int a,int b);

test.cpp

#include "test.h" extern "C" int Add(int a, int b) {     return a + b; } extern "C" int Max(int a, int b) {     if (a > b)         return a;     return b; }

注意:#include "stdafx.h"不要写进去否则编译so库出错,第二需要些extern "C",不写可以编译成so库但是调用会提示undefinedsymbol错误

编译成so库,注意先切换到test.cpp所在目录,可以不用加lib

gcc test.cpp -fPIC -shared -o libtest.so

写成gcc test.cpp -fPIC -shared -o test.so也可以会生成test.so库

python调用

from ctypes import cdll

test = cdll.LoadLibrary(/home/username/Downloads/libtest.so)

result = test.Add(4,5)

print(result)

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-07-25,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • gcc test.cpp -fPIC -shared -o libtest.so
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档