C#使用INT#PTR实现IDL声明
我们在idl文件中声明了如下方法:C#使用INT#PTR实现IDL声明,c#,64-bit,idl,C#,64 Bit,Idl,我们在idl文件中声明了如下方法: [id(7), helpstring("method SomeFunction")] HRESULT SomeFunction([in] INT_PTR windowHandle, [out, retval] VARIANT_BOOL* dlgResult); public bool SomeFunction(IntPtr windowHandle) { // Implementation here. // If you need the v
[id(7), helpstring("method SomeFunction")] HRESULT SomeFunction([in] INT_PTR windowHandle, [out, retval] VARIANT_BOOL* dlgResult);
public bool SomeFunction(IntPtr windowHandle)
{
// Implementation here.
// If you need the value of the pointer in the implementation,
// you can use:
// long actualValue = windowHandle.ToInt64();
}
long actualHandle = 1234;
IntPtr handlePtr = new IntPtr(actualHandle);
bool returnValue = SomeFunction(windowHandle);
我们使用以下方法在C#中实现它:
public bool SomeFunction(int windowHandle)
这在构建32位时效果很好,但是当我们构建x64时,类型不匹配,因为idl正在查找64位值,而c#需要32位值
在C#中使用IntPtr不起作用,因为代码需要在C#中使用long或int
在c#方法中是否有任何类型可以根据平台编译为long或int
我不希望通过两次使用该函数来复制代码,而且由于向后兼容性,我不确定是否可以将IDL更改为只使用Int64
任何帮助都将不胜感激。
谢谢进入项目属性。。。和“生成”选项卡 在那里,您可以找到“条件编译符号”,为您的x64平台添加WIN64。保存 对于“AnyCPU”,您可能希望删除该平台 然后在代码使用中:
#if WIN64
long handle;
public bool SomeFunction(long windowHandle)
#else
int handle;
public bool SomeFunction(int windowHandle)
#endif
但是,我认为您可以使用IntPtr并根据其大小属性将其值转换为int/long…您确定
IntPtr
不适用于您吗?IntPtr
结构有一个构造函数重载,该重载采用Int32
,另一个重载采用Int64
。此外,它还有一个ToInt32()
方法和一个ToInt64()
方法。您的代码的工作方式如下:
[id(7), helpstring("method SomeFunction")] HRESULT SomeFunction([in] INT_PTR windowHandle, [out, retval] VARIANT_BOOL* dlgResult);
public bool SomeFunction(IntPtr windowHandle)
{
// Implementation here.
// If you need the value of the pointer in the implementation,
// you can use:
// long actualValue = windowHandle.ToInt64();
}
long actualHandle = 1234;
IntPtr handlePtr = new IntPtr(actualHandle);
bool returnValue = SomeFunction(windowHandle);
底部的代码看起来可以工作,但这都是C代码。我遇到的问题是,该方法是在IDL文件中声明的,这会导致C#代码出错:csfile.cs(37):“csnamespace.csproject.csfile”未实现接口成员“cpplib.icppineterface.SomeFunction(long)”。无论我在C#方法中使用and int还是IntPtr,在编译x64时都会出现该错误。如果我使用IntPtr,它也不会编译为32位,因为签名专门寻找int;我读得不够仔细。问题恰恰是您在IDL中使用INT_PTR,我假设您正在使用这样一种机制来实现COM兼容性。您可以从IDL的角度查看问题的讨论。是的,它已经12年了,但我认为它仍然与您的情况有关,特别是专门讨论INT_PTR和LONG_PTR的部分。