swig使python能调用C++

来源:互联网 发布:哪里有软件编程学校 编辑:程序博客网 时间:2024/04/27 16:28
 

     总的步骤就是用swig生成相应的cxx,然后再在程序中调用python开放给C++的接口来调用python脚本。

     1、C++头文件

      testSWIG.h

     std::string SWIGFunction();

   class SWIGClass 
   {   public:      SWIGClass( int value );
      void PrintValue();
   protected:      int m_value;   };
   

     2、SWIG 接口文件

        SWIGME.i

 

   /* File : SWIGME.i */
   %module SWIGME 
   %include "std_string.i" 
   /* Let's just grab the original header file here */
   %include "testSWIG.h"

    3、生成SWIGME_wrap.cxx

    打开控制台,进入到前面两个文件所在的目录,输入:

  swig -c++ -python SWIGME.i

    成功的话就会在当前目录下生成SWIGME_wrap.cxx和SWIGME.py两个文件。

   

   4. 动态调用C++代码的python脚本

     test.py

    

   import SWIGME   s = SWIGME.SWIGFunction()   print "Result of SWIGME.SWIGFunction: " + s   print "Creating SWIGME.SWIGClass of 10:"   a = SWIGME.SWIGClass( 10 )   a.PrintValue()   print "Creating SWIGME.SWIGClass of 42:"   b = SWIGME.SWIGClass( 42 )   b.PrintValue()

   5、C++实现代码

     SWIGME.h

      

#include <string>#include <iostream>class SWIGClass{public:    SWIGClass( int value );    void PrintValue();protected:    int m_value;};


     SWIGME.cpp

   

#include "SWIGME.h"SWIGClass::SWIGClass( int value ) : m_value( value ){}void SWIGClass::PrintValue(){ std::cout << "My Value is " << m_value << std::endl;}


6、测试代码

     test.cpp

   

#include "SWIGME.h"#include "SWIGME_wrap.cxx"int main() {    std::cout << "Exporting C++!" << std::endl;    Py_Initialize();                // initialize python    // initialize SWIGME module:    init_SWIGME();    // Import and run swiggy:    PyRun_SimpleString( "import test" );    Py_Finalize();                  // shut down python    return 0;}    

 

如果成功的话,显示结果将为

 

Exporting C++!Result of SWIGME.SWIGFunction: This has been brought to you by the letter CCreating SWIGME.SWIGClass of 10:My Value is 10Creating SWIGME.SWIGClass of 42:My Value is 42


 

 

 

原创粉丝点击