In my application there is a need to pass an absolutely arbitrary object/struct into a C++ function using P/Invoke. According to the Internet, any objects may be passed as C++ structs (they get pinned to a specific memory location for the duration of the call). As I am only interested in data and do not plan to call any method, this matches my needs well enough. However, experiments show that these objects must have [StructLayout(LayoutKind.Sequential)]
attribute, otherwise the code will not compile. Unfortunately the classes are created by other developers and not guaranteed to have this attribute.
To solve this problem, one solution would be to pass an object to a special C# wrapper function that will:
- Retrieve object's properties using
Type.GetProperties
- Dynamically create a struct with the necessary properties and copy values from the object.
- Add
[StructLayout(LayoutKind.Sequential)]
attribute. - Pass this struct into C++ along with the metadata retrieved at step 1 (so that C++ knows what's the object structure and how to read it)
As I am new to C#, I am not certain how to create structs with arbitrary properties and attributes dynamically. What I've found so far is MakeGenericType and ExpandoObject, but what's required is to create a dynamic struct that is not previously defined anywhere - not even as a generic object. Any ideas?