3

Possible Duplicate:
Passing char pointer from C# to c++ function

I have this type of problem:

I have a c++ function with this signature:

int myfunction ( char* Buffer, int * rotation)

The buffer parameter must be filled with space chars ( 0x20 hex )

In C++ i can solve the problem simply doing this:

char* buffer = (char *)malloc(256);
memset(buffer,0x20,256);
res = myfunction (buffer, rotation);

I'm trying to call this function from C#.

This is my p/invoke declaration:

[DllImport("mydll.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern unsafe int myfunction (StringBuilder Buffer, int* RotDegree);

In my C# class i've tried to do this:

StringBuilder buffer = new StringBuilder(256);
buffer.Append(' ', 256);
...
myfunction(buffer, rotation);

but it doesn't work....

Anyone can help me?

Thanks.

Community
  • 1
  • 1
betelgeuse
  • 160
  • 1
  • 2
  • 8

2 Answers2

6

Your p/invoke doesn't look quite right. It should (presumably) use the Cdecl calling convention. You should not use SetLastError. And there's no need for unsafe code.

I would write it like this:

[DllImport("mydll.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern int myfunction(StringBuilder Buffer, ref int RotDegree);

Then call it like this:

StringBuilder buffer = new StringBuilder(new String(' ', 256));
int rotation = ...;
int retVal = myfunction(buffer, ref rotation);

I didn't specify the CharSet since Ansi is the default.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

Try to pass rotation by reference. You might also need to edit the signature of myfunction. Please let me know if the method works.

myfunction (buffer.ToString(), ref rotation);
e_ne
  • 8,340
  • 32
  • 43