Question about DLLIMport

P

Pawel

Hi,

How can i resolve following trouble.
I will import function from WINAPI that receive char pointer

For example:

char* Somefunction (int );

How can i prepare this?

Regards,
Pawel
 
L

Lloyd Dupont

IF the char pointer point to a standart ANSI string you could write (from
memory, maybe a few syntax error)

[DllImport("TheDll", CharSet=CharSet.Ansi)]
public extern static string SomeFunction(int);
 
W

Willy Denoyette [MVP]

Inline
Willy.

Lloyd Dupont said:
IF the char pointer point to a standart ANSI string you could write (from
memory, maybe a few syntax error)

[DllImport("TheDll", CharSet=CharSet.Ansi)]
public extern static string SomeFunction(int);
Never do this.
The Pinvoke layer assumes that the pointer returned was allocated by a call
to CoAllocMem() and will call CoAllocFree() on the pointer returned after
having marshaled the contents to a string object.
But the memory pointed to by char* is not allocated CoAllocMem, so the
CoAllocFree will fail to free the pointer which results in a memory leak.

The correct way to declare a function that returs a char* is:

public extern static IntPtr SomeFunction(int);

And use the Marshal class methods PtrToStringxxx to marshal the pointer
returned to a string.
Substitute xxx for Ansi or Uni depending on the type returned.

Note that the unmanaged side needs to provide and/or document the function
to call in order to free the char* pointer when done with it.

Willy.
 
L

Lloyd Dupont

oops....
some coding in a hurry, not reading the documentation carefully enough,
obviously....


thanks willy!
have to use my custom marshaller then...

Willy Denoyette said:
Inline
Willy.

Lloyd Dupont said:
IF the char pointer point to a standart ANSI string you could write (from
memory, maybe a few syntax error)

[DllImport("TheDll", CharSet=CharSet.Ansi)]
public extern static string SomeFunction(int);
Never do this.
The Pinvoke layer assumes that the pointer returned was allocated by a
call to CoAllocMem() and will call CoAllocFree() on the pointer returned
after having marshaled the contents to a string object.
But the memory pointed to by char* is not allocated CoAllocMem, so the
CoAllocFree will fail to free the pointer which results in a memory leak.

The correct way to declare a function that returs a char* is:

public extern static IntPtr SomeFunction(int);

And use the Marshal class methods PtrToStringxxx to marshal the pointer
returned to a string.
Substitute xxx for Ansi or Uni depending on the type returned.

Note that the unmanaged side needs to provide and/or document the function
to call in order to free the char* pointer when done with it.

Willy.
 

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