将结构从VC ++返回到C# [英] Returning Struct from VC++ to C#
问题描述
我已经用VC ++编写了一个结构.我已经制作了VC ++代码的dll,并使用PInvoke在C#中调用了该dll.
I have written a structure in VC++. I have made a dll of the VC++ code and calling this dll in C# using PInvoke.
VC ++ dll看起来像这样
The VC++ dll looks like this
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <iostream>
#if defined(_MSC_VER)
#include <windows.h>
#define DLL extern "C" __declspec(dllexport)
#else
#define DLL
#endif
struct SYSTEM_OUTPUT
{
int status;
};
DLL SYSTEM_OUTPUT* getStatus()
{
SYSTEM_OUTPUT* output;
output->status = 7;
return output;
}
我正在用C#代码从dll调用getStatus()函数,如下所示;
I am calling the getStatus() function from the dll in my C# code, which looks as follows;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace UsingReturnStructDLL
{
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEM_OUTPUT
{
[MarshalAs(UnmanagedType.I4)]
int Status;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SYSTEM_OUTPUT output;
[DllImport("ReturnStructDLL", EntryPoint = "getStatus")]
[return: MarshalAs(UnmanagedType.Struct)]
public extern static SYSTEM_OUTPUT getStatus();
private void button1_Click(object sender, EventArgs e)
{
try
{
SYSTEM_OUTPUT output = getStatus();
}
catch (AccessViolationException e)
{
label1.Text = e.Message;
}
}
}
}
我想在C#代码中检索结构中的值.通过上面的代码设置,我收到以下错误;
I want to retrieve the values in the struct in my C# code. With the above setup of my code, I am getting the following error;
Cannot marshal 'return value': Invalid managed/unmanaged type combination (Int32/UInt32
must be paired with I4, U4, or Error).
有人可以帮我解决这个问题吗?
Can someone please help me with the issue?
谢谢.
推荐答案
首先使您的C ++代码工作.它是已发布的垃圾邮件,您没有初始化指针.它将因AccessViolation而崩溃.
Make your C++ code work first. It is junk as posted, you don't initialize the pointer. It will crash with an AccessViolation.
在C/C ++中,很难正确返回指向结构的指针 ,您的代码客户端将不知道如何释放内存.它也对P/Invoke编组器造成了严重破坏,它将尝试使用CoTaskMemFree()释放指针.在Vista或更高版本上,这是一个恶作剧,在XP上,这是内存泄漏.
Returning pointers to structures is very hard to get right in C/C++ as well, the client of your code won't know how the memory needs to be released. Which plays havoc on the P/Invoke marshaller as well, it is going to try to release the pointer with CoTaskMemFree(). That's a kaboom on Vista and up, a memory leak on XP.
如果让客户端将指向结构的指针作为参数传递,则所有这些问题都会消失:
All of these problems disappear if you let the client pass a pointer to the structure as an argument:
void getStatus(SYSTEM_OUTPUT* buffer)
然后在C#中变为:
[DllImport("mumble.dll")]
private static extern void getStatus(out SYSTEM_OUTPUT buffer);
这篇关于将结构从VC ++返回到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!