gpt4 book ai didi

c#调用c++ dll传输struct array发生异常

转载 作者:行者123 更新时间:2023-11-30 19:30:36 27 4
gpt4 key购买 nike

C++ header 定义:

#pragma once

#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif

C++函数:

int Detect(Pos* pfps);

C++结构体定义:

struct FaceAngle
{
int yaw;
int pitch;
int roll;
float confidence;
};


typedef struct tagPOINT
{
LONG x;
LONG y;
}
POINT, * PPOINT, NEAR * NPPOINT, FAR * LPPOINT;


struct Pos
{
RECT rcFace;
POINT ptNose;
FaceAngle fAngle;
int nQuality;
BYTE pFacialData[512];
Pos()
{
memset(&rcFace, 0, sizeof(RECT));
memset(&ptNose, 0, sizeof(POINT));
memset(&fAngle, 0, sizeof(FaceAngle));
nQuality = 0;
memset(pFacialData, 0, 512);
}
};

c++调用代码:

void detect()
{
Pos ptfp[10];
Detect(ptfp);
}

================================================== =============================

C# 函数定义:

[DllImport(THFaceDLLName, EntryPoint = "Detect")]
public static extern int Detect([In, Out] Pos[] posArray);

C# 结构体定义:

[System.Runtime.InteropServices.StructLayoutAttribute    (System.Runtime.InteropServices.LayoutKind.Sequential,
CharSet = System.Runtime.InteropServices.CharSet.Ansi, Pack = 1)]
public struct Pos
{
public RECT rcFace;
public POINT ptNose;
public FaceAngle fAngle;
int nQuality;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
byte[] pFacialData;
};


[System.Runtime.InteropServices.StructLayoutAttribute (System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi, Pack = 1)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}

[System.Runtime.InteropServices.StructLayoutAttribute (System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi, Pack = 1)]
public struct POINT
{
public int x;
public int y;
}
[System.Runtime.InteropServices.StructLayoutAttribute (System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi, Pack = 1)]
public struct FaceAngle
{
int yaw;
int pitch;
int roll;
float confidence;
};

C#调用代码:

void detect()
{
Pos[] facePosArray = new Pos[10];
int faceNum = Detect(facePosArray);
}

执行Detect函数后出现“System.AccessViolationException”异常,我应该将 Pos[] 转换为 Intptr 吗?谁能有好的解决方案

最佳答案

我找到了一个可以直接转换c++结构体的工具例如: Software Interface

这是下载地址: --download.microsoft.com/download/f/2/7/f279e71e-efb0-4155-873d-5554a0608523/CLRInsideOut2008_01.exe--

关于c#调用c++ dll传输struct array发生异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50461495/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com