在Python中,如何使用C++函数通过**参数返回已分配的结构数组?

Jon*_*ric 6 python swig

我想在Python工具中使用一些现有的C++代码NvTriStrip.

SWIG通过简单的参数轻松处理功能,但主要功能GenerateStrips要复杂得多.

我需要在SWIG接口文件中放置什么来表明它primGroups实际上是一个输出参数,并且必须清除它delete[]

///////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
bool GenerateStrips( const unsigned short* in_indices,
                     const unsigned int    in_numIndices,
                     PrimitiveGroup**      primGroups,
                     unsigned short*       numGroups,
                     bool                  validateEnabled = false );
Run Code Online (Sandbox Code Playgroud)

仅供参考,这是PrimitiveGroup宣言:

enum PrimType
{
    PT_LIST,
    PT_STRIP,
    PT_FAN
};

struct PrimitiveGroup
{
    PrimType type;
    unsigned int numIndices;
    unsigned short* indices;

    PrimitiveGroup() : type(PT_STRIP), numIndices(0), indices(NULL) {}
    ~PrimitiveGroup()
    {
        if(indices)
            delete[] indices;
        indices = NULL;
    }
};
Run Code Online (Sandbox Code Playgroud)

ʇsә*_*ɹoɈ 1

我不知道如何使用 SWIG 来做到这一点,但您可能需要考虑转向更现代的绑定系统,例如PyrexCython

例如,对于此类情况,Pyrex 使您可以访问 C++ 删除。以下是文档的摘录:

处理

del 语句可应用于指向 C++ 结构的指针以释放它。这相当于C++中的delete。

cdef Shrubbery *big_sh
big_sh = new Shrubbery(42.0)
display_in_garden_show(big_sh)
del big_sh
Run Code Online (Sandbox Code Playgroud)

http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/version/Doc/Manual/using_with_c++.html