Beckhoff / TF6000_ADS_DOTNET_V5_Samples

Sample code for the Version 6.X series of the TwinCAT ADS .NET Packages
https://infosys.beckhoff.com/content/1033/tc3_ads.net/9407515403.html?id=6770980177009971601
BSD Zero Clause License
37 stars 15 forks source link

Wrong complex struct marshalling #45

Closed drvic10k closed 1 year ago

drvic10k commented 1 year ago

I have the following structure:

    public struct SetupAds
    {
        public SetupAds()
        {
        }

        public string MqttIpAddress { get; init; } = "";

        public short LogLevel { get; init; } = 0;

        public string ApiVersion { get; init; } = "";
    }

image

When I retrieve individual fileds, I get correct values back:

image

But retrieving the whole structure is not correct and the string is different every time:

image

RalfHeitmann commented 1 year ago

Sorry, I'm a little bit of context here. You are implementing you own AdsSymbolicServer here? Or what is the situation?

On first sight, hte SetupAds structure is missing the Memory Layout here (and therefore would use Default Marshalling, which doesn't work with dynamic length strings!).

Have you tried to add the StructLayout attribute on your class/struct like this?

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct SetupAds
{
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
        public string MqttIpAddress { get; init; } = "";
        [MarshalAs(UnmanagedType.I2)]
        public short LogLevel { get; init; } = 0;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
        public string ApiVersion { get; init; } = "";
}

You can check the correct marshalling size of your SetupAds struct with

int sz = System.Runtime.InteropServices.Marshal.SizeOf(typeOf(SetupAds));

which should be 164.

drvic10k commented 1 year ago

SetupAds structure is missing the Memory Layout here (and therefore would use Default Marshalling, which doesn't work with dynamic length strings!).

I was not aware of this, I will give it a try thanks

drvic10k commented 1 year ago

it works with the additional attributes, thanks