2010-11-19 107 views
1

嗨,所有 我试图从我的非托管c-dll获取数据。 c函数需要一个指向结构的指针,用一些值初始化结构并完成。这个错误可能在任何地方,即使在C DLL声明。 (我在这做了第一次)调用结构指针的C函数作为参数

这里的C代码h文件:

#ifndef MYFUNCS_H 
#define MYFUNCS_H 

__declspec(dllexport) typedef struct t_Point{ 
int x; 
int y; 
} Point; 

__declspec(dllexport) Point myFuncs(); 
__declspec(dllexport) int getPoint(Point* point); 
#endif 

C-文件:

#include "stdafx.h" 
#include "OpenCVTest.h" 

int getPoint(Point* point){ 
point->x = 4; 
point->y = 2; 
return 0; 
} 

在C#中的包装:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Runtime.InteropServices; 

namespace CSharp_mit_OpenCV 
{ 
    [StructLayout(LayoutKind.Sequential)] 
    public struct Point 
    { 
     public int x; 
     public int y; 
    }; 

    class Wrapper 
    { 
     [DllImport("OpenCV Test.dll", CharSet= CharSet.Auto)] 
     public static extern int getPoint(ref Point point); 

    } 
} 

而使用该包装的c#函数:

Point p = new Point(); 
      Wrapper.getPoint(ref p); 
      textBox1.Text = p.x.ToString(); 
      textBox2.Text = p.y.ToString(); 

有了这个代码,我得到以下运行时错误:

“来的PInvoke函数调用‘CSHARP麻省理工学院的OpenCV CSharp_mit_OpenCV.Wrapper ::用GetPoint!’的不平衡堆栈。这很可能是因为托管的PInvoke签名与非托管目标签名不匹配。检查调用约定和的PInvoke签名的参数相匹配的非托管的目标签名。”

有什么不对吗?请帮帮忙! 谢谢大家!

回答

0

哪个calling convention是使用你的C项目?如果是cdecl (默认IIRC),您需要在您的DllImport属性中明确指定它:

[DllImport("OpenCV Test.dll", CharSet = CharSet.Auto, 
    CallingConvention = CallingConvention.Cdecl)] 
public static extern int getPoint(ref Point point);