Question about DLLIMport

  • Thread starter Thread starter Pawel
  • Start date Start date
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
 
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);
 
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.
 
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.
 
Back
Top