gpt4 book ai didi

Python 将 void 指针作为参数传递给 C 函数(SWIG、Numpy)

转载 作者:太空宇宙 更新时间:2023-11-04 04:58:49 33 4
gpt4 key购买 nike

我需要将指针从 Python 传递给 C 函数。我目前正在尝试使用 SWIG,但我已准备好切换到任何可以解决我问题的方法:)

为了简化我的问题,我在 SWIG 中编写了这个空的 C 函数:

extern void myvoidp(void *p);

我已经设置了我的 .i 和 .c 文件,都可以正常编译并在 Python 中工作。

我想传递一个 Numpy 数组。我可以这样获取 Numpy 数据的内存地址

>>> anp = array([1,2,3])
array([1, 2, 3])
>>> anp.ctypes.data
40546992

我可以像这样使用 ctypes 和 numpy 将其转换为 void *:

>>> anp.ctypes.data_as(ctypes.c_void_p)
c_void_p(40546992)

我尝试了无数种变体。无论我做什么,当我调用我的 C 函数时,我都会收到此错误。

>>> myswig.myvoidp(anp.ctypes.data_as(ctypes.c_void_p))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: in method 'myvoidp', argument 1 of type 'void *'

我不知道如何编写允许我(简单地)将指针传递给我的 C 函数的 Python/numpy 语句。 :-(

最佳答案

我猜你想要接收一个指向 NumPy 数组数据的指针,这样你就可以从 C 访问数组元素。NumPy 附带了 SWIG support。使用起来简单方便。只需下载 numpy.i并将其放在您的项目目录中。

只需将 C 函数的签名从 (void *p) 更改为 (double *data, int length) 并应用 NumPy 类型映射。

test.i

%module example
%{
#define SWIG_FILE_WITH_INIT
#include <stdio.h>

void myvoidp(double *data, int length) {
printf("data = [ ");
for (int i = 0; i < length; ++i) {
printf("%f ", data[i]);
}
printf("]\n");
}
%}

%include "numpy.i"

%init %{
import_array();
%}

%apply (double* IN_ARRAY1, int DIM1) {(double *data, int length)}
void myvoidp(double *data, int length);

test.py

from example import myvoidp
from numpy import array

anp = array([1,2,3])
myvoidp(anp)

调用示例:

$ swig -python test.i
$ clang -Wall -Wextra -Wpedantic -I /usr/include/python3.6m/ -fPIC -shared -o _example.so test_wrap.c -lpython3.6m
$ python3 test.py
data = [ 1.000000 2.000000 3.000000 ]

关于Python 将 void 指针作为参数传递给 C 函数(SWIG、Numpy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51956101/

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