Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# to C++ Array?

Tags:

c++

c#

pinvoke

I have a library provided, which i know uses C++. I imported the DLL as such:
[DllImport("pst")] private static extern int pst_get_sensor(ref PSTSensor sensor); The PSTSensor is a struct, in a C++ example it was defined as such:

struct PSTSensor
{
        char    name[80];       /**< Device name */
        int     id;             /**< Device identifier (for other tracking interfaces */
        float   pose[16];       /**< Device pose estimate as row-major matrix */
        double  timestamp;      /**< Time the data was recorded */
};

The problem is, that besides an Int and a Double, it uses a Float, and more importantly an array. An array is something way different between C# and C++. When using this struct to call pst_get_sensor(ref sensor); the entire development environment crashes on me when running the code.

I currently do my struct in C# like this:

struct PSTSensor{
        public char[] name;
        public int id;
        public float[] pose;
        public double timestamp;
    }

My question is, how do i create an array that C++ understands, and properly returns? Is this even possible?

Thanks a lot in advance, Smiley

like image 739
Smileynator Avatar asked Sep 18 '26 11:09

Smileynator


1 Answers

Your C# struct needs to define the inline array lengths. And the name field is best declared as a string in the C# code. That makes it much easier for you to work with it.

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
struct PSTSensor
{
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string name;
    public int id;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public float[] pose;
    public double timestamp;
}

The struct layout attribute is optional here, because it just re-states default values. But you may choose to keep it in order to be explicit about your intent.

like image 81
David Heffernan Avatar answered Sep 21 '26 01:09

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!