110,533
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
[ComImport]
[Guid("A4E23A7E-C932-4A31-8455-2F137015DCB2")]
public interface INakeTTClass
{
[DispId(1)]
int Add(int a, int b, out int c);
[DispId(2)]
int GetAge();
}
[ComImport]
[Guid("73269D6A-0BB4-46B8-8062-7C8DCDEE81D3")]
public class NakeTTClass : INakeTTClass
{
[DispId(1)]
[PreserveSig] //<---------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public extern int Add(int a, int b, out int c);
[DispId(2)]
[PreserveSig] //<---------------
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
public extern int GetAge();
}
class Program
{
static void Main()
{
NakeTTClass nake = new NakeTTClass();
int sum;
int hresult = nake.Add(3, 4, out sum);
// hresult == S_OK == 0
// sum == 7
hresult = nake.GetAge();
// hresult = 123
}
}
//interface IMyTT : IDispatch{
// [id(1), helpstring("method Add")] HRESULT Add([in] int a, [in] int b, [out,retval] int* c);
// [id(2), helpstring("method GetAge")] HRESULT GetAge(void);
//};
STDMETHODIMP CMyTT::Add(int a, int b, int* c)
{
*c = a + b;
return S_OK;
}
STDMETHODIMP CMyTT::GetAge(void)
{
return (HRESULT)123;
}
Type ComObjType; // invoke COM object by Type.
object ComObj;
string ReturnValue;
// ComObjType = Type.GetTypeFromProgID("Wrox.ProCSharp.COMInterop.Server.COMDemo");
Guid gid = new Guid("78E88924-824D-46E3-87FD-111AC27D7B7A");
ComObjType = Type.GetTypeFromCLSID(gid);
ComObj = Activator.CreateInstance(ComObjType);
object[] ParamArray = new object[3];
ParamArray[0] = 4;
ParamArray[1] = 5;
ParamArray[2] = 0;
//用参数的索引属性来指出哪些参数是一个返回的参数
//对于那些是[in]或ByRef的参数可以不用指定
ParameterModifier[] ParamMods = new ParameterModifier[1];
ParamMods[0] = new ParameterModifier(3); // 初始化为接口参数的个数
ParamMods[0][2] = true; // 设置第三个参数为返回参数
// how to get Hresult.
ReturnValue = (string)ComObjType.InvokeMember("Add",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
ComObj,
ParamArray,
ParamMods,
null,
null);