Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
This is C# DLL code.

C#
// 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

C++
// 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;
}


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

1 solution

It's pretty straight forward:

C++
#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;
}


(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.)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900