vb.net strings passing Win32 Dlls - HELP

M

marfi95

I'm not sure what other groups this should go to, but I'm trying to
write a Win32 DLL that I can call from my vb.net app. I'm having a
real tough time, as this is printing a different char set than what I
expect. I'm not sure if I'm doing something wrong or its not setup
right, but it looks like Chinese characters coming back. Here is all
the code:

Win32 exported function:

int CDllTest::TestFunc3(TCHAR* lStr, int* lLen)
{
TCHAR* x=NULL;

x = (char *)calloc(10000,sizeof(char));
strcpy(x, "abcabcd");
strcpy(lStr, x);

*lLen = strlen(lStr);
return 0;
}

VB.net method:

Declare Auto Function TestFunc3 Lib "TestDLL" (ByVal msg As
StringBuilder, ByRef msgLength As IntPtr) As Integer

Dim s1 As StringBuilder
Dim i2 As IntPtr

s1 = New StringBuilder(1000)
i1 = TestFunc3(s1, i2)
Trace.WriteLine(s1.ToString & " " & i2.ToInt32)

When trace writes s1.tostring, it seems like chinese characters,
however the length is correct, so its got something to do with the way
its marshalled I guess.

Any help would be great !!!!!

Mark
 
M

Mattias Sjögren

x = (char *)calloc(10000,sizeof(char));

You never free the memory you allocate here so the function is
leaking.

strcpy(x, "abcabcd");
strcpy(lStr, x);

Why not just strcpy(lStr, "abcabcd") directly?

You may also want to pass in the size of the lStr buffer to make sure
you don't overrun it.

Declare Auto Function TestFunc3 Lib "TestDLL" (ByVal msg As
StringBuilder, ByRef msgLength As IntPtr) As Integer

Since you used strcpy above I assume you're using an ANSI build of the
DLL where TCHAR becomes char. In that case you shouldn't use the Auto
modifier on your Declare statement because that will cause the string
to be treated as Unicode on recent versions of Windows.

And the msgLength parameter should be of type Integer, not IntPtr.


Mattias
 
M

marfi95

One other thing mattias,

Is it possible to reinitialize a StringBuilder object, or is the
correct way just to keep reallocating new ones ? I want to just create
1 instance of a stringbuilder, then just use it over and over again ?
 
M

Mattias Sjögren

or is the correct way just to keep reallocating new ones ?

There's nothing wrong with it (unless this happens to be a very
performance critical part of your code called in a tight loop and ou
need to reduce the numbe of objects created).


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top