2009-11-11 4 views
2

J'essaie de transmettre certaines chaînes dans un tableau à ma DLL C++.
C#: passer un tableau de chaînes à une DLL C++

La fonction de DLL C++ est:

extern "C" _declspec(dllexport) void printnames(char** ppNames, int iNbOfNames) 
{ 
    for(int iName=0; iName < iNbOfNames; iName++) 
    { 
     OutputDebugStringA(ppNames[iName]); 
    } 
} 

Et en C#, je charge la fonction comme ceci:

[DllImport("MyDLL.dll", CallingConvention = CallingConvention.StdCall)] 
static extern void printnames(StringBuilder[] astr, int size);<br> 

Puis-je configurer/appeler la fonction comme ceci:

List<string> names = new List<string>(); 
names.Add("first"); 
names.Add("second"); 
names.Add("third"); 

StringBuilder[] astr = new StringBuilder[20]; 
astr[0] = new StringBuilder(); 
astr[1] = new StringBuilder(); 
astr[2] = new StringBuilder(); 
astr[0].Append(names[0]); 
astr[1].Append(names[1]); 
astr[2].Append(names[2]); 

printnames(astr, 3); 

En utilisant DbgView, je peux voir que certaines données sont passées à la DLL, mais il est en train d'imprimer garbag e au lieu de "premier", "deuxième" et "troisième".

Des indices?

Répondre

5

Utilisez String [] au lieu de StringBuilder []:

[DllImport("MyDLL.dll", CallingConvention = CallingConvention.StdCall)] 
static extern void printnames(String[] astr, int size); 

List<string> names = new List<string>(); 
names.Add("first"); 
names.Add("second"); 
names.Add("third"); 

printnames(names.ToArray(), names.Count); 

MSDN a more info sur les tableaux marshaling.

Questions connexes