Python与ctypes绑定-在函数中返回多个值
C++ - Python Binding with ctypes - Return multiple values in function
我找到了这个c++ Python绑定的例子:从python调用C/c++ ?根据答案,我创建了一些测试文件:
foo.cpp:
#include <iostream>
#include <utility>
int bar_2(int a, int b){
return a*b;
}
std::pair<int, int> divide(int dividend, int divisor)
{
return std::make_pair(dividend / divisor, dividend % divisor);
}
extern "C" {
int bar_2_py(int a, int b){ return bar_2(a,b); }
std::pair<int, int> divide_py(int d, int div){return divide(d,div);}
}
fooWrapper.py:
#!/usr/bin/env python
from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')
def bar_2(a, b):
res = lib.bar_2_py( a,b )
return res
def divide(d,div):
res = lib.divide_py(d,div)
return res
然后g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
创建libfoo.so
如果我导入它并在iPython中运行函数,我会得到函数"bar_2"的正确值,但"divide"的(部分)错误答案:
from fooWrapper import bar_2, divide
bar_2(10,2) # returns 20, which is right
divide(10,3) # returns 3
显然,返回值对第一个值是正确的(因为10/3 int除法是3)。但是第二个值丢失了。
那么,获得多个值(在本例中为2个整数值)的最佳实践是什么?谢谢!
我不认为ctypes
允许在没有太多样板代码的情况下将std::pair
转换为python元组。特别是因为std::pair
是c++11
标准的一个特性,而ctypes
只适用于c
风格的函数[需要引用/验证]。
我建议使用输出参数, c
方式返回多个值。这个想法很简单,c
-函数通过指针返回它的值,example.c
:
void divide_modulo(int a, int b, int *div, int *rest)
{
*div = a / b;
*rest = a % b;
}
然后编译成一个共享库:
gcc -o libexample.so -shared example.c
libexample.so
现在允许您通过c
中的指针写入python整数,该指针作为参数传递,如下所示:
import ctypes
lib = ctypes.cdll.LoadLibrary('./libexample.so')
def divide_modulo(a, b):
div = ctypes.c_int(0)
rest = ctypes.c_int(0)
lib.divide_modulo(a, b, ctypes.byref(div), ctypes.byref(rest))
return (div.value, rest.value)
print(divide_modulo(11, 4))
当div
和rest
调用lib.divide_modulo
时,ctypes.byref
包装器将int
转换为指向int
的指针。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数