PtrToStructure for pointer allocated in C++

A

alexia

Hello all,

My C# application gets pointer to a struct allocated in C++ on the
heap using new.
The structure in C++ is:
typedef struct _H
{
int a;
char c[3];
}H;

My C++ does the following:

H * pMSG = new H;
and call C# application.

In my C# application I declared the struct as
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct H
{
public int a;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)]
public string TextLogMsg;
}

How can I cast the InPtr the C# gets to relevant C# struct?
thank you for your reply.
 
P

Peter Duniho

alexia said:
Hello all,

My C# application gets pointer to a struct allocated in C++ on the
heap using new.
The structure in C++ is:
typedef struct _H
{
int a;
char c[3];
}H;

My C++ does the following:

H * pMSG = new H;
and call C# application.

In my C# application I declared the struct as
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct H
{
public int a;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)]
public string TextLogMsg;
}

How can I cast the InPtr the C# gets to relevant C# struct?

It's hard to say for sure without a complete code example. But probably
if you use the System.Runtime.InteropServices.Marshal class and call the
PtrToStructure() method, that will handle the conversion for you.

Though, if that's true, then it means it's probably better for you to do
let the p/invoke layer do the marshaling for you rather than trying to
interpret the pointer explicitly. Again, without a complete code
example that shows what you mean by "call C# application", it's hard to
know for sure, and impossible to provide an exact example of how to
write the code. But typically, with the correct [MarshalAs] attributes,
you can come up with some kind of declaration that will do what you want.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top