Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ C C# Visual-Studio COM
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;
}
 
Problem is how to make interface pointer "pICalc" Global.
Posted 14-Oct-12 23:35pm

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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;
}
 
(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.)
  Permalink  

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

  Print Answers RSS
0 DamithSL 320
1 OriginalGriff 235
2 Afzaal Ahmad Zeeshan 154
3 Sergey Alexandrovich Kryukov 147
4 BillWoodruff 135
0 OriginalGriff 7,510
1 DamithSL 5,494
2 Sergey Alexandrovich Kryukov 4,954
3 Maciej Los 4,936
4 Kornfeld Eliyahu Peter 4,514


Advertise | Privacy | Mobile
Web02 | 2.8.141223.1 | Last Updated 15 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100