liunx python调用c++库(类、函数),传入传出参数

本文详细介绍了如何在Python中调用C++编译的动态库,包括新建C++类和函数,编译动态库,以及在Python中通过ctypes加载库并传递不同类型参数(如cv::Mat,cv::Rect等)的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、使用c++封装动态库

参考文献http://www.linuxidc.com/Linux/2012-09/70502.htm

1.新建test类

1.1新建 test.cpp 文件

代码如下:

#include<iostream>

           extern "C" 

           int myadd(int a, int  b) 

           { 

                    return a + b; 

            }

备注:extern"C" 必须有,不然会报undefined symbol: myadd.


1.2新建test.h文件

代码如下:

#ifndef _TESTSO_H  

                   #define_TESTSO_H  

                   extern"C"  

                   { 

                            intmyadd(int a, int b); 

                            typedefint myadd_t(int, int); // myadd function type  

                   } 

                   #endif// _TESTSO_H 

备注:test.h文件可以没有,因为test.cpp也没有#include <test.h>,再说myadd()函数也不是类的成员函数。


2.编译

g++  -shared -fPIC  -o test.so test.cpp

 

备注1:

-fPIC:生成位置无关目标代码,适用于动态连接;

-L path:表示在path目录中搜索库文件,如-L.表示在当前目录;

-I path:表示在path目录中搜索头文件;

-o file:制定输出文件为file;

-shared:生成一个共享库文件;

备注2:

编译多个cpp文件:

g++ -shared-fPIC -o demo.so demo.cpp CCNF_patch_expert.cpp LandmarkDetectorFunc.cppLandmarkDetectorModel.cpp LandmarkDetectorUtils.cppLandmarkDetectorParameters.cpp LandmarkDetectionValidator.cpp Patch_experts.cppPAW.cpp PDM.cpp SVR_patch_expert.cpp stdafx.cpp$(pkg-config opencv --cflags --libs) $(/usr/lib/x86_64-linux-gnu/libboost_filesystem.so;/usr/lib/x86_64-linux-gnu/libboost_system.so)-I /usr/include/boost -L /usr/lib/x86_64-linux-gnu/ -I boost_system –l boost_filesystem

(在使用上面命令代码编译时,先将代码放到txt中,写成一行,最后在赋值到命令行进行编译,不然可能会出错)

,最好是写个makefile文件来编译。

3. C++方式调用库

3.1新建main.cpp

         代码如下:

   

                   #include <stdio.h>  
                   #include <dlfcn.h>   //必须有
                   #include <iostream>
                   #include"test.h"                    // for dynamic library函数  

                   int main(int argc, char*argv[]) 
                   { 
                           if (2 != argc)
                           { 
                                 return-1; 
                           } 
                            const char *soname =argv[1];        
                            void *so_handle = dlopen(soname,RTLD_LAZY); // 载入.so文件  
                            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值