Declaring a struct, usable from C#, in managed C++

2019-07-24 23:24发布

问题:

I have a scenario where a C# library is consuming a mixed mode C++ library. The use case is as follows:

1) The C# code initializes a listener from the library (managed c++), which initializes a listener from native C++.

2) The native code receives a message and parses it, then passes it to the managed c++ via IJW code

3) The managed c++ calls a delegate from the C# code with the message

This all works fine, except for the very last part - actually including the message. The C# code can't access the data type defined in the managed C++. When you navigate to the struct's definition, it looks like this:

namespace NativeWrapper
{
   [CLSCompliant(false)]
   [NativeCppClass]
   [UnsafeValueType]
   public struct MyDataType
   {
   }
}

As you can see - it decries it as unsafe and wipes out the fields. I've seen solutions to this problem where a third library, in C#, declares a struct, and both the C# and the managed C++ use it. I imagine that would work, but I'm trying to avoid creating a third library for one small file...this component is part of a large system, I'd like to keep the number of DLLs I'm adding to it as small as possible.

So, the question is, is there a way I can define a struct in managed C++ that the C# code can references? I know how to define a ref class, that's how my listener is set up, but I'd like this to be a struct.

标签: c# c++-cli