how to call c++ function in python coding in linux?
2017-04-10 11:25
357 查看
本文想要讲清楚的是在linux系统上,在python coding 时候调用c++ function。
对于要被python调用的c++ function的coding,并没有太大特殊,只是在function定义的时候,前面加上:
接下来,就是编译c++ function,生成.so文件,供python 调用。
这里提供cmake方式的编译。在当前工程目录下新建CMakeLists.txt,如下例子(假设函数仅使用opencv库)供参考,要注意的是,projectname不要和functionname重复。
完成之后,cd 到你的工程目录下,
如果你的代码没有bug,步骤也都正确了,那么恭喜你,你已经生成 了 .so 文件。可以进入python调用了。
好啦,已经成功调用了~
对于要被python调用的c++ function的coding,并没有太大特殊,只是在function定义的时候,前面加上:
extern "C" void functionname(...) { ...}
接下来,就是编译c++ function,生成.so文件,供python 调用。
这里提供cmake方式的编译。在当前工程目录下新建CMakeLists.txt,如下例子(假设函数仅使用opencv库)供参考,要注意的是,projectname不要和functionname重复。
set(OpenCV_DIR "/home/westwell/opencv-2.4.13/release") cmake_minimum_required(VERSION 2.8) project( projectname) find_package( OpenCV REQUIRED ) find_package(PythonInterp) find_package(PythonLibs) include_directories( ${OpenCV_INCLUDE_DIRS} (path to your project) ) #add_executable( projectname functionname.cpp ) PYTHON_ADD_MODULE(projectname functionname.cpp) target_link_libraries( projectname ${OpenCV_LIBS} )
完成之后,cd 到你的工程目录下,
cd (path to your project) cmake . make
如果你的代码没有bug,步骤也都正确了,那么恭喜你,你已经生成 了 .so 文件。可以进入python调用了。
import ctypes as C project = C.cdll.LoadLibrary('/path to your so/projectname.so') project .functionname()
好啦,已经成功调用了~
相关文章推荐
- how to write a DLL/SO in C/C++ for Python
- How to call a service function in AngularJS ng-click
- How to Use the Dynamic Link Library in C++ Linux (C++调用Delphi写的.so文件)
- What is EPOLL? Epoll vs Poll vs Select call ? And How to implement UDP server in Linux using EPOLL?
- How to install and manage different versions of Python in Linux
- How to uninstall/update/ your python in Linux
- 【转】How to call c++ exported method and classes in c#
- how to call the member function?( C++ ) . or ->
- how to call javascript function in webview
- How to Use `strace` to Trace the System Call in Linux
- What is EPOLL? EPOLL vs Select call? And How to implement UDP server in Linux using EPOLL?
- How to call C/C++ sytle function from C# solution?
- How to programmatically clear the filesystem memory cache in C++ on a Linux system?
- How to write Lossfunction in PythonCaffe
- How can I force Python's file.write() to use the same newline format in Windows as in Linux (“\r\n”
- The study of how to define a function in Python(20170907)
- How to call c++ exported method and classes in c#
- How to reimplement (or wrap) a syscall function in linux?
- How to separate the implementation and definition for template function in c++
- How to fix Fatal error: Call to undefined function: mysql_connect() in Ubuntu