返回C++双到Python?

2024-10-02 20:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在共享C++库中使用Python调用方法。我有一个问题,从C++返回到Python的一个倍数。我有一个创造了一个玩具的例子,展示了这个问题。请随意编译并试用它。在

这是python代码(soexample.py)公司名称:

# Python imports
from ctypes import CDLL
import numpy as np

# Open shared CPP library:
cpplib=CDLL('./libsoexample.so')
cppobj = cpplib.CPPClass_py()

# Stuck on converting to short**?
x = cpplib.func_py(cppobj)
print 'x =', x

这里是C++示例.cpp)公司名称:

^{pr2}$

编译时使用:

g++ -fPIC -Wall -Wextra -shared -o libsoexample.so soexample.cpp

当我跑步时,我得到:

$ python soexample.py
x = 0

因此结果是一个类型为且值为0的整数。发生什么事?在

我还想通过引用填充数组。在


Tags: 方法pyimport名称so公司cppshared
1条回答
网友
1楼 · 发布于 2024-10-02 20:39:10

来自ctypes documentation

By default functions are assumed to return the C int type. Other return types can be specified by setting the restype attribute of the function object.

如果将func_py的用法更改为以下内容,则可以使用它:

import ctypes

func_py = cpplib.func_py
func_py.restype = ctypes.c_double
x = func_py(cppobj)
print 'x =', x

虽然它可能适用于这个简单的情况,但您还应该指定CPPClass_py.restype。在

相关问题 更多 >