calling C/C++ DLL that takes a pointer to LPTSTR

  • Thread starter Thread starter Sam Carleton
  • Start date Start date
S

Sam Carleton

The C definition is along the lines of:

LONG SetFilenames( LONG nFiles, LPCSTR* lpFileNames);

Where the lpFileNames is an array of LPCSTR's.

The ultimate DLL that needs to be called is a 3rd party's module,
but there is a C/C++ DLL which is a wrapper for the 3rd party
module, this wrapper is called directly by C#. There does not
appear that such a method signature can be called direct from C#.
What tactic should be used to get a collection of strings from C#
to the wrapper class? A fellow developer suggested that I define
a struct in C# that simply contains a string. I know that it
would work, but it is messy and I am looking for a more straight
forward, cleaner approach. Any ideas?

Sam
 
Sam,

Is lpFileNames written to? If not, then just pass it as an array. I
assume you would have to pass a null string at the end of the array, but
that should translate just fine.

Also, make sure you do not use long in C# when defining this function.
Use int (LONGs in C/C++ are 32 bit integers).

Hope this helps.
 
Sam,

Is lpFileNames written to? If not, then just pass it as an array. I
assume you would have to pass a null string at the end of the array, but
that should translate just fine.

Also, make sure you do not use long in C# when defining this function.
Use int (LONGs in C/C++ are 32 bit integers).

Thanks, I have been using Int32 in C# for a C/C++ LONG, is that
correct or is there a more ideal type to use in C#?

Sam
 
Sam,

Int32/int (int is the C# alias for Int32) is the correct type to use for
LONGs in C/C++.
 
Sam Carleton said:
The C definition is along the lines of:

LONG SetFilenames( LONG nFiles, LPCSTR* lpFileNames);

Where the lpFileNames is an array of LPCSTR's.

The ultimate DLL that needs to be called is a 3rd party's module,
but there is a C/C++ DLL which is a wrapper for the 3rd party
module, this wrapper is called directly by C#. There does not
appear that such a method signature can be called direct from C#.
What tactic should be used to get a collection of strings from C#
to the wrapper class? A fellow developer suggested that I define
a struct in C# that simply contains a string. I know that it
would work, but it is messy and I am looking for a more straight
forward, cleaner approach. Any ideas?

Sam

You can simply pass it as an array of string pointers, like this...

extern "C" {
__declspec(dllexport) void __stdcall func_c2 ( int len, LPCSTR* ar);

}

int __stdcall SetFilenames(int len, LPCSTR* ar)
{
printf_s("Len %d\n", len);
for (int n = 0; n < len ; n++)
{
printf_s("%s\n", ar[n]);
}
return ...;
}

in C#
[DllImport("your.dll")]
// Marshaled as Ansi strings by default.
private static extern int SetFilenames(int len, string[] ar);

...
string[] ar = new string[5];
for (int n = 0;n < ar.Length ;n++ )
{
ar[n] = "String" + n.ToString();
}
SetFilenames(ar.Length, ar);

Willy.
 
Back
Top