【发布时间】:2021-04-09 05:23:00
【问题描述】:
我需要修改我从 cython 传递给 c++ 函数的 NumPy 数组。一切正常,但是当我在调用 c++ 修饰函数后打印出该值时,该值与调用该函数之前的值保持不变。我也对字符串进行了同样的尝试,但也没有成功。我使用键入的内存视图来访问内存。以下是我使用的代码(仅保留与此问题相关的相关内容)
test.h
#include <iostream>
struct S1 {
float* buffer;
int length;
};
int modify(S1* s1, char* str);
test.cpp
#include "test_modify.h"
int modify(S1* s1, char* str) {
str = "newstr"; // string modify
int out_idx = 0;
while(out_idx < s1->length) {
s1->buffer[out_idx++] = 10; // array modify
}
return 0;
}
test.pyx
from numpy import pi, cos, sin, arccos, arange
import numpy as np
cimport numpy as np
np.import_array()
cdef extern from "test_modify.h":
cdef struct S1:
float* buffer
int length
int modify(S1* s1, char* str)
def modifyPY():
d = np.zeros((2, 3, 3), dtype=np.float32)
cdef float[:, :, ::1] d_view = d.astype(np.float32)
cdef S1 s1 = [&(d_view[0, 0, 0]), np.product(d.shape)]
cdef char *s = 'jhk'
modify(&s1, s)
return d, s
** setup.py**
from setuptools import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import numpy
extensions = [
Extension("temp",
sources=["test.pyx", "test_modify.cpp"],
include_dirs=[numpy.get_include()],
extra_compile_args=["-O3", '-std=c++11'],
language="c++")
]
setup(
ext_modules=cythonize(extensions)
)
# to install run, python setup.py build_ext --inplace
test.py(构建后运行)
import temp
d, s = temp.modifyPY()
print(d) # still 0's, should be 10's
print(s) # still "jhk" should be "newstr'
【问题讨论】:
-
test.pyx 中的
depthBuffer是什么?它没有定义。 -
你的代码没有编译,请提供minimal reproducible example。
-
我希望更改
S1中的数组能够正常工作(除了我们不知道w和h),而不是字符串。 -
我已经用应该构建的最小可重现示例更新了代码。我使用 cython 0.29.21 版本进行构建。谢谢
-
当你打印 d 和 s 时,输出是什么?
标签: python c++ numpy pointers cython