简体   繁体   English

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

[英]Python passing void pointer as parameter to C function (SWIG, Numpy)

I need to pass a pointer from Python to a C function. 我需要将指针从Python传递到C函数。 I'm currently trying with SWIG but I'm ready to switch to anything that will solve my issue :) 我目前正在尝试使用SWIG,但我准备切换到任何可以解决我的问题的方法:)

To simplify my problem, I wrote this empty C function in SWIG: 为了简化我的问题,我在SWIG中编写了这个空的C函数:

extern void myvoidp(void *p);

I've setup my .i and .c files, all compile fine and work in Python. 我已经设置了.i和.c文件,都可以正常编译并且可以在Python中工作。

I'd like to pass a Numpy array. 我想传递一个Numpy数组。 I can get the memory address of the Numpy data like this 我可以这样获取Numpy数据的内存地址

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

I can cast it to a void * like this with ctypes and numpy: 我可以使用ctypes和numpy将其强制转换为void *:

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

I've tried endless variants. 我尝试了无尽的变体。 Whatever I do, when I invoke my C function I get this error. 无论我做什么,当我调用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 *'

I can't figure out how to write a Python / numpy statement that allows me to (simply) pass a pointer to my C function. 我不知道如何编写一个Python / numpy语句,该语句允许我(简单地)将指针传递给C函数。 :-( :-(

I guess you want to receive a pointer to the data of the NumPy array, so that you can access the array elements from C. NumPy ships with SWIG support which is easy and convenient to use. 我猜想您想接收一个指向NumPy数组数据的指针,以便可以从C访问该数组元素。NumPy附带了SWIG支持 ,使用简单方便。 Just download numpy.i and place it in your project directory. 只需下载numpy.i并将其放置在您的项目目录中即可。

Just change the signature of the C function from (void *p) to (double *data, int length) and apply the NumPy typemap. 只需将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)

Example invocation: 调用示例:

$ 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 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM