How to treat output arguments like char** array in python?

烂漫一生 提交于 2021-02-04 08:39:05

问题


I am trying to call C methods from Python script but I am facing an issue while calling the method which outputs char** array as an argument. the method in C layer as follows. helper.c file:

//This method takes filename as input and oNames as output
  extern C int GetNames(char* iFilename, char** oNames)
{
    int oNumNames, oStatus;
    /*io* pIo = GetIoInstance();*/
    std::vector<EString> names;
    CreateIoInstance(iFilename);
    oStatus = pIo->get_names(names);
    oNumNames = (int)names.size();

    for (int ii = 0; ii < oNumNames; ii++)
    {
        strcpy(oNames[ii], names[ii].c_str());
    }
    return 0;
}

Please help me with calling this method from python script.

from ctypes import *

dll = CDLL('D:\\python\\working.dll')
dll.GetNames = dll.GetNames
dll.GetNames.argtypes = (c_char_p, POINTER(c_char_p))
dll.GetStageNames.restype = c_int

filename = "in.h5"
def GetNames(filename):
    ostagenames = POINTER(c_char_p)
    err = dll.GetStageNames(filename, ostagenames)
    return err, ostagenames.value

回答1:


I've simplified the function to focus on the char** parameter. As your sample function was written it assumes memory was pre-allocated, but there is no interface to indicate the size of the array used for output or the individual strings in the array. In this example, the memory is pre-allocated for a 3-element array with a maximum of 20 characters per string, but in reality the user would have to pre-allocate enough strings with enough length to hold the return values in the real-life situation.

test.cpp:

#define API __declspec(dllexport)
#include <vector>
#include <string>
#include <cstring>

using namespace std;

//This method takes filename as input and oNames as output
extern "C" API void GetNames(char** oNames)
{
    vector<string> names { "one", "two", "three" };
    for (size_t i = 0; i < names.size(); ++i) {
        strcpy(oNames[i], names[i].c_str());
    }
}

test.py:

from ctypes import *

dll = CDLL('./test')
dll.GetNames.argtypes = POINTER(c_char_p),
dll.GetNames.restype = None

def get_names():
    ARR3 = c_char_p * 3  # equivalent to char*[3] type in C

    # list of 3 mutable pointers to buffers
    buffers = [cast(create_string_buffer(20),c_char_p) for _ in range(3)]

    names = ARR3(*buffers) # array initalized with buffers
    dll.GetNames(names)
    return list(names)

print(get_names())

Output:

[b'one', b'two', b'three']

If you are free to change the API, allocating memory dynamically so it can be freed later makes it more flexible. This is rather ugly with a char*** but it works:

test.cpp:

#define API __declspec(dllexport)
#include <vector>
#include <string>
#include <cstring>

using namespace std;

extern "C" {

API void GetNames(char*** oNames) {
    vector<string> names { "one", "two", "three" };
    auto arr = new char*[names.size() + 1];
    for (size_t i = 0; i < names.size(); ++i) {
        auto len = names[i].size() + 1;
        arr[i] = new char[len];
        strcpy_s(arr[i], len, names[i].c_str());
    }
    arr[names.size()] = nullptr;
    *oNames = arr;
}

API void FreeNames(char** names) {
    if(names) {
        for(size_t i = 0; names[i]; ++i)
            delete [] names[i];
        delete [] names;
    }
}

}

test.py:

from ctypes import *

# ctypes.c_char_p has special handling for strings,
# but hides the pointer value.  Deriving a type
# from c_char_p prevents this special handling
# and allows access to the pointer, so we can later
# free it.
class PCHAR(c_char_p):
    pass

dll = CDLL('./test')
dll.GetNames.argtypes = POINTER(POINTER(PCHAR)),
dll.GetNames.restype = None
dll.FreeNames.argtypes = POINTER(PCHAR),
dll.FreeNames.restype = None

def get_names():
    pnames = POINTER(PCHAR)() # allocate char**
    dll.GetNames(byref(pnames)) # pass char***
    i = 0
    names = []
    while pnames[i]:  # returned char* array is terminated with null
        names.append(pnames[i].value) # create and save the Python byte string
        i += 1
    dll.FreeNames(pnames)
    return names

print(get_names())

Output:

[b'one', b'two', b'three']


来源:https://stackoverflow.com/questions/64120648/how-to-treat-output-arguments-like-char-array-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!