Passing a structure of data from VC++ to C#?
I want to transfer a structure of data to an application which is create开发者_StackOverflowd in C#. I will be filling the structure in a VC++ program.
How can I send it? Is structure suppported in C#?
Or else if I use LPDATA in VC++: how can I get the same thing in C#?
Defining the struct in C#
When defining your struct in C# make sure you use datatypes which match the C++ implementations. Char in C++ as Byte in C# etc...
You need to add some attributes to ensure your struct memory layout in C# matches the C++ implementation
[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]
public struct MyStruct
{
}
Passing the struct
Declare a struct in C# using the same data structure. Pass a pointer to the struct to your C# app from C++ and cast it to the new struct in C#.
Calling you C# dll
For calling your C# DLL, your best option is to use a mixed mode assembly in C++. This allows you to use the pragmas managed
and unmanaged
to switch between native and managed code. This way you can nicely wrap you C# class with a workable C++ wrapper. See this Microsoft article. Be aware though, this is not supported on Mono.
Yes, structure is supported and can be used. Strings may require a bit of work, however.
Show us your structure. C# has marshaller helpers to map its types to native c++ types easily, you just have to know how to decorate your types, and we can help with that if you show us your structure.
For example, that LPDATA thing you mentioned, if that's char *
, it maps directly over byte[]
in C# if it's a generic buffer, or string
if it's a normal string (the string
mapping requires marshaller help, but it's a lot easier to use once decorated properly).
You could learn a lot from the "platform invoke tutorial" on MSDN. The only difference is that you'll be invoking your own DLL :)
精彩评论