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.

3
  • 2
    "but it doesn't work" is not helpful. Commented Dec 21, 2012 at 16:09
  • 3
    You didn't even show the p/invoke declaration! We can't help you without fundamental information like that. Commented Dec 21, 2012 at 16:12
  • @FrancisP This question is not a duplicate of that one! Commented Dec 21, 2012 at 16:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.