gpt4 book ai didi

python - CPPYY/CTYPES 将字符串数组作为 char* args[] 传递

转载 作者:行者123 更新时间:2023-12-01 13:37:59 25 4
gpt4 key购买 nike

我最近才开始使用 cppyyctypes ,所以这可能是一个有点愚蠢的问题。我有以下 C++ 函数:

float method(const char* args[]) {
...
}

从 Python 我想通过 args作为字符串列表,即:
args = *magic*
x = cppyy.gbl.method(args)

我之前找到了 this ,所以我用
def setParameters(strParamList):
numParams = len(strParamList)
strArrayType = ct.c_char_p * numParams
strArray = strArrayType()
for i, param in enumerate(strParamList):
strArray[i] = param
lib.SetParams(numParams, strArray)

并来自 Python:
args = setParameters([b'hello', b'world'])
c_types.c_char_p需要一个字节数组。但是,当调用 x = cppyy.gbl.method(args)我明白了
TypeError: could not convert argument 1 (could not convert argument to buffer or nullptr)

我不完全确定为什么这是错误的,因为 args<__main__.c_char_p_Array_2>对象,我认为应该将其转换为 const char* args[] .

最佳答案

为了有一个具体的例子,我将使用它作为 .cpp文件:

#include <cstdlib>

extern "C"
float method(const char* args[]) {
float sum = 0.0f;
const char **p = args;
while(*p) {
sum += std::atof(*p++);
}
return sum;
}

我假设它是用 g++ method.cpp -fPIC -shared -o method.so 编译的.鉴于这些假设,下面是一个如何从 Python 中使用它的示例:

#!/usr/bin/env python3

from ctypes import *

lib = CDLL("./method.so")
lib.method.restype = c_float
lib.method.argtypes = (POINTER(c_char_p),)

def method(args):
return lib.method((c_char_p * (len(args) + 1))(*args))

print(method([b'1.23', b'45.6']))

我们创建一个 C 数组来保存 Python 参数。 len(args) + 1确保有空指针标记的空间。

关于python - CPPYY/CTYPES 将字符串数组作为 char* args[] 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62009589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com