【问题标题】:Cython modifiy pointer from c++Cython 从 C++ 修改指针
【发布时间】: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 中的数组能够正常工作(除了我们不知道 wh),而不是字符串。
  • 我已经用应该构建的最小可重现示例更新了代码。我使用 cython 0.29.21 版本进行构建。谢谢
  • 当你打印 d 和 s 时,输出是什么?

标签: python c++ numpy pointers cython


【解决方案1】:
cdef float[:, :, ::1] d_view = d.astype(np.float32)

Docs:

默认情况下,astype 总是返回一个新分配的数组

d_viewd 的副本的视图,而不是 d 的视图。因此,我们预计 d_view 所做的更改不会反映在 d 中。


int modify(S1* s1, char* str) {
    str = "newstr"; // string modify

这是一个基本的 C 指针传递问题。 Python 中的strs 都指向同一个地方,但它们是不同的指针。在strstr = "newstr" 中重新分配后,它们现在指向不同的位置。

您可能想要一个指向指针的指针 (char**)?

【讨论】:

  • 它按预期工作。谢谢。我不知道 astype 返回一个新分配的数组。 Aso,自从我使用 C++ 以来已经有好几年了,所以忘记了大部分概念。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2021-12-19
相关资源
最近更新 更多