如何使接口指针全局化? [英] How to make the interface pointer global?

查看:90
本文介绍了如何使接口指针全局化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C#DLL代码.

This is C# DLL code.

// Class1.cs
// A simple managed DLL that contains a method to add two numbers.
using System;

namespace ManagedDLL
{
	// Interface declaration.
    public interface ICalculator
    {
        int Add(int Number1, int Number2);
    };

    // Interface implementation.
	public class ManagedClass:ICalculator
	{
       public int Add(int Number1,int Number2)
            {
                return Number1+Number2;
            }
	}
}



这是客户代码



This is the client code

// CPPClient.cpp: Defines the entry point for the console application.
// C++ client that calls a managed DLL.

#include "stdafx.h"
#include "tchar.h"
// Import the type library.

#import "..\ManagedDLL\bin\Debug\ManagedDLL.tlb" raw_interfaces_only
using namespace ManagedDLL;
int _tmain(int argc, _TCHAR* argv[])
{
    // Initialize COM.
    HRESULT hr = CoInitialize(NULL);

    // Create the interface pointer.
    ICalculatorPtr pICalc(__uuidof(ManagedClass));

    long lResult = 0;

    // Call the Add method.
    pICalc->Add(5, 10, &lResult);

    wprintf(L"The result is %d\n", lResult);


    // Uninitialize COM.
    CoUninitialize();
    return 0;
}



问题是如何使接口指针"pICalc"成为全局指针.



Problem is how to make interface pointer "pICalc" Global.

推荐答案

很简单:

It''s pretty straight forward:

#include "stdafx.h"
#include "tchar.h"
// Import the type library.

#import "..\ManagedDLL\bin\Debug\ManagedDLL.tlb" raw_interfaces_only
using namespace ManagedDLL;

ICalculatorPtr pICalc = NULL;

int _tmain(int argc, _TCHAR* argv[])
{
    // Initialize COM.
    HRESULT hr = CoInitialize(NULL);
 
    // Create the interface pointer.
    pICalc = ICalculatorPtr(__uuidof(ManagedClass));
 
    long lResult = 0;
 
    // Call the Add method.
    pICalc->Add(5, 10, &lResult);
 
    wprintf(L"The result is %d\n", lResult);
 

    // Uninitialize COM.
    CoUninitialize();
    return 0;
}



(顺便说一句,我想这只是一个示例,因为您的托管DLL在接口,类和方法上需要一些属性,并且必须是ComVisible.)



(BTW, I suppose this is just a sample, because your managed DLL needs some attributes on the interfaces, classes and methods and must be ComVisible.)


这篇关于如何使接口指针全局化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆