Jump to content
Xtreme .Net Talk

Recommended Posts

Posted
I have a C++ library (with managed extensions). A function returns a char*. I want to call this function from C#. How can I access the char*?
  • *Experts*
Posted

When you declare the DLL function, use a byte[] or char[]. Either can easily be turned into a String in .NET.

 

-Nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

When I try writing a C++ function my unmanaged C++ class which returns a char[], I get a compiler error C3409 empty attribute block is not allowed. Am I doing something wrong?

 

thanks

Bryan

Posted

Probably because it thinks you're trying to return an array. Your char* was fine.

 

I believe Nerseus was talking about using char[] in your .NET code when you declare the DLL function, not the C++ code.

Gamer extraordinaire. Programmer wannabe.
  • 6 months later...
Posted

Marshaling return value

 

I also have a C++ library (without managed extensions). A function returns a char*. I want to call this function from C#. How can I access the char*?

I tried to use byte[] or char[] but I am having a problem because

as soon as I call my C++ function, I get an exception thrown with a message "Cannot marshal return value".

Here is the code that calls C++ function

byte[] charAr = new byte[41];

charAr = Region.RegionMgr_GetStateAbbrev(80);

Posted

one option

 

this is the code to convert the other way.

 

fname is a managed type String. ufname is an unmnaged char*.

 

void* pfname = Marshal::StringToHGlobalAnsi(fname).ToPointer( );

char* ufname = (char*)pfname;

Marshal::FreeHGlobal((int)ufname);

 

I see in the Marshal class, there is a method

 

Marshal.PtrToStringUni Method

 

which copies an unmanaged Unicode string to a managed String object.

 

and

 

Marshal.PtrToStringAnsi Method

 

Perhaps you can figure out what to do from there.

 

Bryan

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...