美文网首页
简单python混编C++

简单python混编C++

作者: BigBigGuy | 来源:发表于2019-02-27 16:15 被阅读0次

1、主要是通过将.cpp文件转为.so文件,才给python利用。.so文件又称(share object)

$ g++ -o lib.so -shared -fPIC name.cpp

譬如:

main.h

#ifndef MAIN_H
#define MAIN_H

#define HELLO  "hello world"

#endif

main.cpp

#include <iostream>
#include "main.h"

using namespace std;

class TestLib
{
  public:
    void display();
    void display(int a);
};

void TestLib::display()
{
    cout << "First display" << endl;
    cout << HELLO << endl;
}

void TestLib::display(int a)
{
    cout << "Second display: " << a << endl;
}

extern "C"
{
    TestLib obj;
    void display()
    {
        obj.display();
    }
    void display_int(int a)
    {
        obj.display(a);
    }
}

hello.py

from  ctypes import cdll

so = cdll.LoadLibrary
lib = so("./libmain.so")
lib.display()
a = 100
lib.display_int(a)
print("a : %d"%a)

相关文章

网友评论

      本文标题:简单python混编C++

      本文链接:https://www.haomeiwen.com/subject/qrhxuqtx.html