好的我有一个声明为:
的DLL函数[DllImport(mDllName, EntryPoint = "SetParam")]
public static extern bool setParam(string param_name, ref IntPtr param_value);
这个函数采用了很多不同的参数,即在C ++中,这就是你如何使用它。
int i=2;
setParam("width", &i);
float k=2.5f;
setParam("factor", &f);
所以我试图声明一个C#函数来调用这个DLL api,我有一个工作用于指向整数的情况:
public static void setWidth(int width)
{
IntPtr w = new IntPtr(width);
setParam("width", ref w);
}
但我无法弄清楚如何做第二个我将指针传递给浮点数作为IntPtr。有什么想法吗?
public static void setFactor(float f)
{
IntPtr w = new IntPtr(f); // WHAT GOES HERE??
setParam("factor", ref w);
}
答案 0 :(得分:2)
如果您必须使用IntPtr
并且无法传递float
参数,则可以使用unsafe
编码将float
指针传递为{ {1}}在其构造函数之一中将IntPtr
指针作为参数。但是,相应的非托管函数也必须使用void
指针。
有两种方法可以解决这个问题:传递void
或传递void*
。我会说传递IntPtr*
可能更好,因为你通常会对void*
做同样的事情,除了IntPtr
将用指针而不是函数传递。
选项1 -
IntPtr
首先必须通过删除错误的IntPtr
ref
您也不会将[DllImport(mDllName, EntryPoint = "SetParam")]
public static extern bool setParam(string param_name, IntPtr param_value);
作为IntPtr
传递,只需传递ref
的实例
IntPtr
或者如果您想要身体中的不安全声明
public static unsafe void setFactor(float f)
{
IntPtr w = new IntPtr(&f);
setParam("factor", w);
}
选项2 -
public static void setFactor(float f) { unsafe { IntPtr w = new IntPtr(&f); setParam("factor", w); } }
void*
然后您可以将其设置为
[DllImport(mDllName, EntryPoint = "SetParam")]
public unsafe static extern bool setParam(string param_name, void* param_value);
对于public static unsafe void setWidth(int width)
{
int* w = &width;
setParam("width", w);
}
float