将结构从非托管C ++传递到C# [英] Passing struct from unmanaged C++ to C#

查看:149
本文介绍了将结构从非托管C ++传递到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:最后的工作解决方案是编辑之后!

Note: The final working solution is after the edit!

我希望有人能帮助我解决一个问题以解决最近几天。

I hope someone can help me with a problem I've been trying to solve for the last few days.

我试图将结构从非托管C ++ DLL传递到C#脚本。这是我到目前为止:

I am trying to pass a struct from a unmanaged C++ DLL to a C# script. This is what I have so far:

C ++

EXPORT_API uchar *detectMarkers(...) {
    struct markerStruct {
            int id;
    } MarkerInfo;

    uchar *bytePtr = (uchar*) &MarkerInfo;

    ...

    MarkerInfo.id = 3;
    return bytePtr;
}

C#

[DllImport ("UnmanagedDll")] 
    public static extern byte[] detectMarkers(...);

...

[StructLayout(LayoutKind.Explicit, Size = 16, Pack = 1)]
public struct markerStruct
{
    [MarshalAs(UnmanagedType.U4)]
    [FieldOffset(0)]
    public int Id;
}

...

markerStruct ByteArrayToNewStuff(byte[] bytes){
    GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
    markerStruct stuff = (markerStruct)Marshal.PtrToStructure(
        handle.AddrOfPinnedObject(), typeof(markerStruct));
    handle.Free();
    return stuff;
}

...

print(ByteArrayToNewStuff (detectMarkers(d, W, H, d.Length) ).Id);

问题是这样工作,但打印的值完全关闭有时候最大的int值)。

The problem is that this works, but the value printed is completely off (sometimes it prints around 400, sometimes max int value).

我猜想有一些问题,我如何编组C#中的结构。任何想法?

I'm guessing that there's something wrong with how I marshalled the struct in C#. Any ideas?

编辑

C ++

struct markerStruct {
    int id;
};

...

EXPORT_API void detectMarkers( ... , markerStruct *MarkerInfo) {
    MarkerInfo->id = 3;
    return;
}

C#

[DllImport ("ArucoUnity")] 
    public static extern void detectMarkers( ... ,
        [MarshalAs(UnmanagedType.Struct)] ref MarkerStruct markerStruct);

...

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct MarkerStruct
{
    public int Id;
}

...

detectMarkers (d, W, H, d.Length, ref markerInfo);      
print( markerInfo.Id );


推荐答案

您返回一个指向局部变量的指针已经被销毁之前.NET可以读取它。这是一个坏主意在纯C ++和一个坏主意与p / invoke。

You're returning a pointer to a local variable which has already been destroyed before .NET can read it. That's a bad idea in pure C++ and a bad idea with p/invoke.

而是,有C#传递一个结构的指针(只是使用 ref 关键字)和C ++代码只是填充它。

Instead, have C# pass a pointer to a structure (just use the ref keyword) and the C++ code just fill it in.

这篇关于将结构从非托管C ++传递到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆