Oliver
Oliver

Reputation: 69

Calling a C++ function that takes a char pointer from C#

I cant figure out how to pass a char * to this C++ function from C#.

extern "C" __declspec(dllexport)
unsigned int extractSegment(char * startPoint, unsigned int sizeToExtract)
{
//do stuff
shared_ptr<std::vector<char>> content(new std::vector<char>(startPoint,startPoint+sizeToExtract));
//do more stuff
return content->size();
}

This function is used to read a segment from a file and do some binary operations on it (why i use the vector of chars). The startPoint is the start of the segment i want to read. I cannot change this function.

In C# I tried reading the file into a byte[] array and defining the DllImport to use StringBuilder where the export had char *. I tried to call it as such:

byte[] arr = File.ReadAllBytes(filename);
StringBuilder sb = new StringBuilder(System.Text.Encoding.Unicode.GetString(arr, startPoint,arr.Length - startPoiunt));
extractSegment(sb,200);

This resulted in SEHException.

Upvotes: 1

Views: 2373

Answers (1)

Dirk
Dirk

Reputation: 10958

A char * can have several different meanings. In your case it appears to be a preallocated and filled array of bytes that is used as an input parameter for the extractSegment function.

The equivalent C# method would then take a byte[] parameter, i.e.

[DllImport(...)]
public static extern int extractSegment(byte[] startPoint, uint sizeToExtract);

I use byte[] because you mention binary operations, however if it is actually a string then you can also marshal it as such, setting the correct encoding in the DllImport attribute.


And just for further information, other possible options for char * that I can think of right now would be ref byte, out byte, ref char, out char or string. StringBuilder on the other hand is used when the calling function allocates and returns a string, i.e. char **.

Upvotes: 1

Related Questions