Привет, я обертываю библиотеку C++ с помощью C#. Следующая функция в C++:Функция PInvoke с указателем на параметр указателя
SCREENCAPTUREDLL_API wchar_t** getAudioDeviceList(int* listSize) {
static std::vector<wchar_t*> descriptionList;
AudioCaptureList::getInstance().Update();
AudioCaptureList::getInstance().getList(&descriptionList);
*listSize = descriptionList.size();
return &descriptionList[0];
}
Обертывания с следующими C# код:
[DllImport(screenCaptureDLLPath, CallingConvention = callConversion)]
private static extern IntPtr getAudioDeviceList(ref int arrayCount);
public static string[] GetAudioDeviceList()
{
IntPtr outputStr;
int length = 0;
outputStr = getAudioDeviceList(ref length);
string[] resultArray = new string[length];
for (int j = 0; j < length; j++)
{
resultArray[j] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(outputStr, 4 * j));
}
return resultArray;
}
Это отлично работает, точно так, как я ожидал, но я собирался изменить способ, которым я возвращающийся значение из функции себя переменным по ссылке, поэтому я меняю код:
C++
SCREENCAPTUREDLL_API void getAudioDeviceList(wchar_t** list, int* listSize) {
static std::vector<wchar_t*> descriptionList;
AudioCaptureList::getInstance().Update();
AudioCaptureList::getInstance().getList(&descriptionList);
*listSize = descriptionList.size();
list = &descriptionList[0];
}
C#
[DllImport(screenCaptureDLLPath, CallingConvention = callConversion)]
private static extern void getAudioDeviceList(out IntPtr listRef, ref int arrayCount);
public static string[] GetAudioDeviceList()
{
IntPtr outputStr;
int length = 0;
getAudioDeviceList(out outputStr, ref length);
string[] resultArray = new string[length];
for (int j = 0; j < length; j++)
{
resultArray[j] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(outputStr, 4 * j));
}
return resultArray;
}
Но я получил ошибку, возвращенный адрес памяти равен нулю. В чем проблема? Пожалуйста, помогите мне понять, в чем причина проблемы и как ее исправить, спасибо!
Право, я попробовал listRef = & descriptionList [0]; – Liastre
@ Liastre Если этот ответ помог вам решить проблему, вы можете [отметить это как принято] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). –
Удивительно, что работает, спасибо! – Liastre