您的位置:首页 > 编程语言 > C语言/C++

python调用c++ 函数

2013-06-05 08:07 507 查看
一、环境搭建
1.安装boost库,配置环境变量D:\boost_1_52_0;D:\boost_1_52_0\stage\lib;
2.修改C:\Users\Administrator\AppData\Local\Microsoft\MSBuild\v4.0下的Microsoft.Cpp.Win32.user.props及Microsoft.Cpp.x64.user.props文件
在<IncludePath>D:\boost_1_52_0\;</IncludePath>
在<LibraryPath>D:\boost_1_52_0\stage\lib;</LibraryPath>
3.安装python配置环境变量D:\Python27\include;
2.修改C:\Users\Administrator\AppData\Local\Microsoft\MSBuild\v4.0下的Microsoft.Cpp.Win32.user.props及Microsoft.Cpp.x64.user.props文件
在<IncludePath>节点处添加D:\boost_1_52_0\;
在<LibraryPath>节点处添加D:\boost_1_52_0\stage\lib;
二、代码示例
创建dll工程
=====================================
hello.cpp
#include <iostream>
using namespace std;
class hello {

public:
string hestr;
private:
string title;
public:
hello(string str){

this->title = str;
}
string get() {

return this->title;
}
};
==========================================
hc.h
#pragma once
#include "hello.cpp"

class hc:public hello{

public:
hc(string str);
~hc(void);
int add(int a,int b);
};
=============================================
#include "hc.h"

hc::hc(string str):hello(str){

}

hc::~hc(void){

}

int hc::add(int a,int b){

return a+b;
}
========================
pyhello.cpp 连接桥梁
#include "hc.h"
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
class_<hello>("hello",init<std::string>())
.def("get",&hello::get)
.def_readwrite("hestr",&hello::hestr);
class_<hc,bases<hello>>("hc",init<std::string>())
.def("add",&hc::add);
}
编译生成dll
将生成的dll文件 修改为hello_ext.pyd
===========================================
python调用
import hello_ext
he=hello_ext.hello("testddd")
print he.get()

he.hestr="ggggddd"
print he.hestr

te=hello_ext.hc("ffff")
print te.get()
te.hestr="ddffg"
print te.hestr
print te.add(33,44)
运行结果




本文出自 “享受编程” 博客,请务必保留此出处http://demidroid.blog.51cto.com/2954092/1216346
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: