python调用C和C++代码(BOOST)

Boost.Python: 初步介绍 Boost.Python介绍 Boost.Python简单概括:是Boost库的一部分;用来在C++代码中调用python代码以及在Python代码中调用C++代码,并且避免用户直接操作指针。 BoostPython库让C++和Python几乎无缝结合,是Boost库的一个功能。 用BoostPython库,能快速、容易地将C++输出到Python,使得Python接口和C++接口非常像。它 阅读详情

本文使用了Boost中有关Python的部分,并着重介绍如何用C++写的函数或是类,并让Python能调用。先看我们设计好的C++函数和类。

#include <string>
#include <windows.h>

//定义一个函数
void msgbox(const std::string& str)
{
    MessageBox(0,str.c_str(),"msgbox",MB_OK);
}

//定义一个C++类
class Hello
{
public:

    std::string m_str;

public:

    Hello()
    {
     MessageBox(0,"Called Hello:Hello()","Hello",MB_OK);
    }

    void SetMsg(const std::string & str)
    {
     m_str=str;
    }

    void ShowMsg()
    {
     MessageBox(0,m_str.c_str(),"Hello",MB_OK);
    }
};

  要导出成Python能使用的类和函数模块,我们用boost中python模块来实现。

#include <boost/python.hpp>

BOOST_PYTHON_MODULE(pyTest)//这个pyTest即在Python中引用的模块名,用Import导入。并且和Dll的名称需要一模一样才行,扩展名可以由DLL自己保留。
{
using namespace boost::python;

//导出C++类,注意格式,还有里面有init后面,如果构造函数有参数,需要在这里面加入
class_<Hello>("Hello",init<>())
    .def("SetMsg",&Hello::SetMsg)           //映射成员函数
    .def("ShowMsg",&Hello::ShowMsg)//映射成员函数
    ;

//导出一个C函数,供调用
def("msgbox", msgbox);          //映身函数
}

这里,还需要新建一个DLL工程,将这两个源码加入工程,编译成一个DLL。

以下是在Python中调用:
from pyTest import *

megbox('调用C函数,我是DLL中的函数')

h = Hello()
h.SetMsg('我是在脚本中被调用的')
h.ShowMsg()

用IDLE载入,并按F5,就可以执行脚本了。
python 调用c/c++ 阅读详情

相关推荐

MDT部署实战:除了Office,这些“装机必备”软件也能一键静默安装(含静默参数)

本文详细介绍了如何利用Microsoft Deployment Toolkit(MDT)实现企业级软件的静默安装,包括浏览器、开发工具和系统增强工具等“装机必备”软件的部署方案。通过命令行参数和MSI属性,IT运维团队可以高效构建标准化工作环境,提升部署效率并确保版本一致性。文章还提供了安装顺序控制、结果验证和常见问题排错等高级技巧。

weixin_26985923的博客 172

python怎么调用c++的类和成员函数

在 Python 中调用 C 语言的类和成员函数,通常需要使用 Cython 或 ctypes 库。 使用 Cython 的方法: 安装 Cython:在命令行中输入 pip install cython 即可安装。 编写 Cython 代码:在 Python 中创建一个 .pyx 文件,然后使用 Cython 语法编写代码。例如,下面是示例代码: cdef extern from"my_...

weixin_35751412的博客 712

用 Coze 打造纯自动化 AI 情报助手

本文将引导您逐步构建一个简易的AI情报助手,从提示词到工作流,再到卡片消息,详细讲解了如何利用Coze平台开发自动化工具。过程简单易懂,何不亲自动手一试?如果您对此类内容感兴趣,敬请关注本作者。未来,我将带来更多精彩的AI工具教程,助您迅速掌握各类AI应用。在这个AI时代,让您领先一步。t=O83A2AGI.NET AI 教程 震撼!用 Coze 打造纯自动化 AI 情报助手震撼!

xinzhaobuxuan的博客 2531

Python调用C++

python被称为胶水语言,其优势是能够粘结各种不同的语言。同时,python有着更大的“亲民性”,很容易进行开发。但是,python最大的问题就是。通常可以用CUDA或者C++对一个python程序进行加速,加速策略如下:大规模算术运算、矩阵运算等过程用底层语言编写,python只负责传参和处理结果数据;十分常用的函数,我们可以用C++写成“算子”,然后python调用算子即可,如边缘检测的Sobel算子;

呆呆象呆呆的博客 1万+

IC设计新手必看:如何正确使用去耦电容(decap)避免电源噪声?

本文深入探讨了IC设计中去耦电容(decap)的应用技巧,从核心原理到布局实现,帮助新手工程师有效抑制电源噪声。文章详细解析了MIM、MOM等电容类型的特性与选择策略,并提供了先进的布局技巧和验证方法,特别适用于28nm以下先进工艺的电路设计挑战。

weixin_30555125的博客 114

ZEMAX学习第7天-手机镜头光学系统设计全过程案例

接下来对系统微调,依次缩小CRA和畸变,首先对CRA进行依次递减(39°、38°、37°、36°、35°),目前CRA角度40度,每次下降一度进行优化,利用MAXX加OPLT一起控制,控制小于35°。可以看出在标注的三个地方镜头曲率变化,导致PY=1的光线走向奇特,因此需要对矢高进行调整,按照标注的地方依次调整(从右到左)至传函变好,越靠近右边对其余视场影响越小。3.圆锥系数值较大,透镜形状怪异;一、第1,3镜子偏厚,第4镜子偏薄,45镜子间隔边缘偏小,第5片镜子中心厚度与边缘厚度相差较大,需要控制;

liningliwei的博客 1067

Python实例浅谈之三Python与C/C++相互调用

一、问题       Python标识符必须以字母或下划线开头,后面跟字母、下划线或者数字,且标识符不能为关键字,如何有效的检查? 二、解决 1、方法一 (1)python脚本 三、总结 (1)Python代码性能的分析和提高还需要不停的总结,在循环中尽量不要重复计算值不变的字符串。 (2)若有更好的设计或思路,请留言,在此先感谢!

乌托邦 10万+

Saturn PCB Toolkit V8.02 实战:5分钟完成10A电源路径的走线与过孔通流验证

本文详细介绍了如何使用Saturn PCB Toolkit V8.02快速验证10A电源路径的走线与过孔通流能力。通过实战案例和参数配置指南,帮助工程师解决大电流PCB设计中的温升失控、过孔瓶颈等核心挑战,提升设计效率和可靠性。

weixin_34194829的博客 451

Python调用C++类(续)

这个月时间过得真快,又到了月底了。回想起来,一个月下来,学到的东西可不少啊,感觉很充实,很好!这次继续总结一下Python调用C++类的点点滴滴吧,开动!      上次说过PyArg_ParseTuple可以很神奇的转化基类与子类的关系,原来这只是在某些条件下才成立的。例如:

永远的ACE 2060

Isaac Sim 使用经验(配置要求,云服务器)

Google Colab及AutoDL都是在docker内运行,其中google colab并不支持docker指令,而依照AutoDL的相关文档,AutoDL并不直接提供docker指令。2. Google Colab/AutoDL 不支持图形化界面,图形渲染等任务,所以没有办法使用Omniverse Streaming进行直播,从而更好的对结果进行展示。对于第一点,或许存在直接手动复现镜像的可能,但是考虑到Isaac Sim/Isaac Lab由于比较新,可能不够稳定,因此还是按照官方文档进行部署。

weixin_44211433的博客 4587

信贷模型域——清收阶段模型(贷后模型)

本文深入探讨了信贷模型域中的清收阶段模型(贷后模型),涵盖早期催收模型(C卡)、晚期催收模型、Best Time to Contact模型和回收模型。这些模型通过多维度数据输入,运用分类、回归和生存分析等建模方法,输出关键指标如还款概率、回收率等,广泛应用于银行、资产管理公司和催收外包公司,助力提升回款率、优化资源分配、降低催收成本,并融入贷后风控体系。

庄小焱 653

python调用C++

前言 大家都知道Python的优点是开发效率高,使用方便,C++则是运行效率高,这两者可以相辅相成,不管是在Python项目中嵌入C++代码,或是在C++项目中用Python实现外围功能,都可能遇到Python调用C++模块的需求,下面列举出集中c++代码导出成Python接口的几种基本方法,一起来学习学习吧。 原生态导出 Python解释器就是用C实现,因此只要我们的C++的数据结构能让P...

Don't worry,be happy 861

基于JeecgBoot 3.9.0 开源项目的企业管理平台

基于JeecgBoot 3.9.0 开源项目的企业管理平台

宁波阿成的博客 374

python调用c++动态库_ubuntu中python调用C/C++方法之动态链接库详解

安装boostpython调用C/C++的方法有很多,本文使用boost.python。考虑到后期有好多在boost上的开发工作,所以boost一并安装了,Boost库分为两个部分来使用,一是直接使用对应的头文件,二是需要编译安装相应的库才可以使用。具体安装方法可以参考:https://www.jb51.net/article/150380.htm这里使用:sudo apt-get install...

weixin_39610678的博客 124

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

python什么模块动态调用链接库_ubuntu中python调用C/C++方法之动态链接库详解

安装boostpython调用C/C++的方法有很多,本文使用boost.python。考虑到后期有好多在boost上的开发工作,所以boost一并安装了,Boost库分为两个部分来使用,一是直接使用对应的头文件,二是需要编译安装相应的库才可以使用。这里使用:sudo apt-get install libboost-all-dev服务端序列化后发送main.cpp:#include #inclu...

weixin_39811478的博客 201

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python调用cpp_Python调用C/C++的种种方法

Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过.1. Python 调用 C (base)想在python中调用c函数, 如这儿的fact#includeint fact(int n){if (n <= 1)return 1;elsereturn ...

weixin_39980347的博客 1550

Python调用C/C++的种种方法

<br />Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过.<br /> <br />1. Python 调用 C (base)<br />想在python中调用c函数, 如这儿的fact<br />#include <Python.h><br /><br /> int fact(int n)<br /> {<br />   if (n <= 1)<br /

日知录 12万+

利用Boost.Python实现Python C/C++混合编程

关于python与C++混合编程,事实上有两个部分 extending 所谓python 程序中调用c/c++代码, 其实是先处理c++代码, 预先生成的动态链接库, 如example.so, 而在python代码中import example;即可使用c/c++的函数 . embedding c++代码中调用 python 代码. 两者都可以用 python c 转换api,解决,具体可以去py...

章志强的专栏 1117

Python和C|C++的混编(一):Python调用C、C++---Boost库

不使用boost.python库来直接构建dll的话比较繁琐,下面实例是借助boost库实现python对C、C++的调用 1 首先确定已经安装python和boost库,本例测试环境是python2.7,boost_1_54_0 ,在vs平台下实现 2 vs建立dll工程,vs下boost库的环境配置参加上篇博文,记得包括python的依赖库:E:\Python27\include和E:\P

求知若饥,知行合一 9617

Python调用C++代码

Python调用C++代码 今天在研究PyTorch中Tensor的一些操作的时候,发现其底层Tensor的操作都是用C++写的,并使用pybind11进行C++和Python的桥接。所以,我就想着探索一下Python中如何调用C++代码? 可行方案 其实,方案还是挺多的: Python内置的ctypes接口(可以将C/C++代码编译为动态库,在Python中进行调用) CFFI(提...

给永远比拿愉快 9013

boost python嵌入_boost.python入門教程 ----python 嵌入c++

boost.python 中 python 嵌入c++ 部分,網上找到的中文資料似乎都有些過時了,如 boost.python學習筆記 http://edyfox.codecarver.org/html/boost_python.html在boost.python版本2中,提供更加簡潔易用的接口,我們可以使用從而代替原始的PyRun_SimpleString等等python c 轉換api.關於p...

weixin_26757939的博客 193

python 调用 c函数 numpy 数组_从Python调用C函数并将OpenCV Mat转换为Numpy数组

Background situation我试图通过Python绑定使用OpenCV Stitching模块,但是我收到一个错误:import cv2stitcher = cv2.createStitcher(False)imageL = cv2.imread("imageL.jpg")imageC = cv2.imread("imageC.jpg")imageR = cv2.imread("ima...

weixin_39645003的博客 566

python调用c/c++方式示例(修改整理)

Python是解释性语言, 底层就是用c实现的, 所以用python调用C是很容易的, 下面就总结一下各种调用的方法, 给出例子, 所有例子都在ubuntu9.10, python2.6下试过.   1. Python 调用 C (base) 想在python中调用c函数, 如这儿的fact #include int fact(int n) { if (n <= 1) re

固本培元的专栏 1708

boost python_基于 Boost 库实现的 Python 调用 C++ 接口

接触到的很多开源项目都由纯 C++ 转到 Python + C++了,我也因此一直心向往之,今天动手实验了一下,发现并没有很复杂(初步观察)。趁热把这个过程记录下来,也免得明天到办公室就忘了。。其实做Python 和 C++ 的接口有很多种方式,比如Swig,Cython,Boost 等。我用Boost是因为之前贡献过代码的一个项目用的就是这种方式,不想跳其他坑了而已。所以这里并没有要尝试去比较几...

weixin_39845206的博客 556
上一篇: C++扩展和嵌入Python应用
下一篇: Windows汇编语言开发环境
b2b160
博客等级 码龄20年 2408粉丝 96原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值