【问题标题】:How to correctly declare unmanaged DLL function?如何正确声明非托管 DLL 函数?
【发布时间】:2017-04-26 14:00:14
【问题描述】:

我试图在我的 C# 应用程序中调用非托管 DLL 的函数。函数声明为this。该函数将来自采集板的数据写入文件(即,来自数组 real_dataimag_data)。

我正在使用以下声明,但文件包含不正确的数据,我认为声明是错误的:

[DllImport(@"C:\SpinCore\SpinAPI\lib32\spinapi.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int pb_write_ascii_verbose(string fname, int num_points, float SW, float SF, ref int[] real_data, ref int[] imag_data);

用法:

pb_write_ascii_verbose(@"C:\Users\Public\direct_data_0.txt", numberOfPoints, (float)actualSW, (float)sequence.Frequency, ref idata, ref idata_imag);

这声明正确吗?如果是这样,正确的声明是什么?

【问题讨论】:

  • hmm spincore 确实提供了 .Net 包装器,但它们是 beta 版本,目前尚不清楚它们有多新(在他们的网站上他们谈论 vs 2008 !!!!),无论如何你可以看看这里:@ 987654322@
  • 您知道这是什么类型的 DLL,您在尝试调用时是否遇到错误?尝试将您的 CallingConvention 更改为 StdCall
  • @Alex Dmitry Egorov 的回答有效。
  • @niceman 谢谢你的建议。

标签: c# function pinvoke declaration unmanaged


【解决方案1】:

您需要给 Interop 一个提示,将数组编组为 LPArray。在这种情况下不需要ref

[DllImport(@"C:\SpinCore\SpinAPI\lib32\spinapi.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int pb_write_ascii_verbose(
    string fname, 
    int num_points, 
    float SW, 
    float SF, 
    [MarshalAs(UnmanagedType.LPArray)]
    int[] real_data, 
    [MarshalAs(UnmanagedType.LPArray)]
    int[] imag_data);

【讨论】:

  • 谢谢!我测试了你的答案,没问题。
【解决方案2】:

你不需要ref int[],你声明的是“一个指向数组的指针”。

您的 DLL 函数需要一个数组。

[DllImport(@"C:\SpinCore\SpinAPI\lib32\spinapi.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int pb_write_ascii_verbose(string fname, int num_points, float SW, float SF, int[] real_data, int[] imag_data);

【讨论】:

    猜你喜欢
    • 2014-10-08
    • 1970-01-01
    • 2018-03-14
    • 2012-07-24
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多