Bonjour Je suis en train d'encapsuler la bibliothèque C++ avec C#. Fonction suivante en C++:Fonction PInvoke avec paramètre pointeur vers pointeur
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];
}
Emballage avec la prochaine code 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;
}
qui fonctionne parfaitement, exactement comme je m'y attendais, mais je suis sur le point de changer la façon dont je valeur de retour elle-même de la fonction à la variable par référence, donc je changer mon code:
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;
}
Mais j'ai eu une erreur, l'adresse mémoire retournée est zéro. Quel est le problème ici? S'il vous plaît aidez-moi à comprendre ce qui cause le problème et comment y remédier, merci!
A droite, j'ai essayé listRef = & descriptionList [0]; – Liastre
@Liastre Si cette réponse vous a aidé à résoudre le problème, alors vous pouvez le [marquer comme accepté] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). –
Génial, ça marche, merci! – Liastre