Error Pointers and fixed size buffers may only be used in an unsafe context

rangers99
rangers99 used Ask the Experts™
on
Hello

Im developing a windows application using Visual C# and Visual Studio 2008.

Ive written a DLL (myDLL.dll) in C/C++ that has the following function;

 __declspec(dllexport) int  SE_GetErrorMessage(char *pError, int BufferSize);

int GetMessage(char *pError, int BufferSize)
{
      // code in here
}

Basically pError is a pointer to an error message


In my C# code I have

[DllImport(@"myDLL.dll")]
int GetMessage(char* pError, int BufferSize);

The above C# definition causes the following error on compilation:
"Error Pointers and fixed size buffers may only be used in an unsafe context"


Is there an easy to fix this?

Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Use a String instead of char*.  C# is normally a managed language.  Pointers are only allowed within unsafe blocks of code.

http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=351



[DllImport(@"myDLL.dll")]
int GetMessage(String pError, int BufferSize);

Open in new window

>>>> Pointers are only allowed within unsafe blocks of code.
You may have mixed code assemblies when using managed C++.

But when using C# you would need to using marshaling when passing a pointer to a function. I don't know how that is made in C# but from managed C++ I would assume you have to provide a byte array which later can be converted to a String by passing it as argument to a new String. Note, String always handles wide characters (wchar_t in C++) while char is 8bit single char.

Author

Commented:
Just noticed a small mistake in my question

"SE_GetErrorMessage()" should  be "GetMessage"
masheikSoftware Engineer
Commented:
how to use unsafe code in c# , refer here,
http://msdn.microsoft.com/en-us/library/aa288474(VS.71).aspx

Author

Commented:
OBonio
That works!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial