Hi..

I am working with vb.net .. I am new in vc++. I need to write some code in vc++ in some case. I need vc++ for following reason.

I created one dll in vb.net and make a tlb file based on vb.net dll. I import physical tlb file in my vc++ code with static value, as mentioned following.

#import "C:\Documents and Settings\Ankit.ass\My Documents\Visual Studio 2010\Projects\SetupValidationPro\SetupValidationPro\bin\Debug\SetupValidationPro.tlb" named_guids raw_interfaces_only

That's work fine.. My problem is that, I want to create a tlb file dynamically or runtime using vc++ and load that tlb file dynamically.

So, I need to embed a dll in vc++. How can I embed dll in vc++?

Now, I want to extract my embed dll to some physical file. so how can I extract my dll to physical location in vc++?

And, at the last step I want to create a tlb file dynamically using that extracted dll using vc++.. and load tlb file dynamically.

How can I achieve this?

Thanks

Ankit

Dani AI

Generated

solved the core problem by embedding the managed DLL (and a RegAsm helper) as resources, extracting them at runtime and registering the assembly so the COM type is available. The pattern works, but a few practical clarifications, safer defaults and alternatives make the approach more robust.

Use RT_RCDATA and write the raw bytes with WriteFile (simpler and less fragile than mapping and memcpy). Keep resource lookups with MAKEINTRESOURCE and check each API return. Example extraction helper (native Win32):

bool SaveResourceToFile(HMODULE hMod, int resId, const wchar_t* outPath)
{
    HRSRC hrs = FindResourceW(hMod, MAKEINTRESOURCEW(resId), RT_RCDATA);
    if (!hrs) return false;
    HGLOBAL hg = LoadResource(hMod, hrs);
    void* p = LockResource(hg);
    DWORD sz = SizeofResource(hMod, hrs);
    HANDLE hf = CreateFileW(outPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hf == INVALID_HANDLE_VALUE) return false;
    DWORD written = 0;
    BOOL ok = WriteFile(hf, p, sz, &written, NULL);
    CloseHandle(hf);
    return ok && written == sz;
}

Notes about type library creation and registration: #import is a compile-time facility — a TLB generated at runtime cannot be #imported after the EXE is built. To consume a runtime-generated TLB use LoadTypeLib/LoadRegTypeLib + IDispatch/ITypeInfo or generate the TLB programmatically and register the assembly from managed code (TypeLibConverter or AssemblyRegistrationServices) or by calling RegAsm. If using RegAsm, run the RegAsm.exe whose bitness matches the target assembly (Framework vs Framework64) and elevate to administrative rights when registry registration is required.

Security and lifecycle: write extracted files to a transient, per-process directory (GetTempPath / SHGetKnownFolderPath), use unique filenames (GUID or GetTempFileName), delete files and undo registration on uninstall, and avoid shipping RegAsm unless necessary. For fewer privileges and cleaner deployments, prefer registration-free COM (manifest) or programmatic registration via the CLR hosting / interop APIs.

Hi,

I resolve the issue after lots of googling.. This is the code from where my issue is resolve. I don't need native code for this..

#include "stdafx.h"
#include "stdafx.h"
#include <Msi.h>
#include <WinUser.h>
#include "windows.h"
#include <afxwin.h>
#include <afx.h>
#include <WinSpool.h>
#include <assert.h>
#include <WinBase.h>
#include "resource.h"


#define IDR_DLL1 101
#define IDR_EXE1 102

bool ExtractDll(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename);
bool ExtractExe(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename);

bool cmd();
CString AppPath();

#define RtlCopyMemory(Destination,Source,Length) memcpy((Destination),(Source),(Length))

#import "dv.tlb" named_guids raw_interfaces_only

using namespace dv;

UINT __stdcall Validation( MSIHANDLE hModule )
{
    /*BOOL qw = ExtractDll(AfxGetResourceHandle(), IDR_DLL1, _T("C:\\VBDLL.dll") );
    BOOL qw1 = ExtractExe(AfxGetResourceHandle(), IDR_EXE1, _T("C:\\RegAsm.exe") );*/

    BOOL qw = ExtractDll(AfxGetResourceHandle(), IDR_DLL1, (LPCTSTR)(AppPath() + _T("\\dv.dll")) );
    if (qw == false)
    {
        return ERROR_INSTALL_USEREXIT;
    }
    BOOL qw1 = ExtractExe(AfxGetResourceHandle(), IDR_EXE1, (LPCTSTR)(AppPath() + _T("\\RegAsm.exe")) );
    if (qw1 == false)
    {
        return ERROR_INSTALL_USEREXIT;
    }
    BOOL retCmd = cmd();

    if (retCmd==false)
    {
        return ERROR_INSTALL_USEREXIT;
    }
   

    IkeyvalidationPtr pICalc(__uuidof(SetupClass));

    long retun =0;

    BSTR strVer = SysAllocString(L"4.0.1517");

    pICalc->keyValidation(strVer,&retun);
    if (retun==1)
    {
        return ERROR_INSTALL_USEREXIT;
    }

    return ERROR_SUCCESS;
}
CString AppPath()
{
    try
    {
    TCHAR path [MAX_PATH];

    ITEMIDLIST* pidl;

    HRESULT hRes = SHGetSpecialFolderLocation( NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE , &pidl );
    if (hRes==NOERROR)
    {
     SHGetPathFromIDList( pidl, path);
    }

    CString apPath;
    apPath = path;
    apPath = apPath + _T("\\path");

    CreateDirectory((LPCWSTR) apPath,NULL);
    return apPath;
    }
    catch(...)
    {

    }
}
bool cmd()
{
    CString m1=_T('');
    CString temp1 = _T("");
    CString temp = temp1 + _T('"');
    //CString s1 = temp + AppPath() + _T("\\RegAsm.exe");        // Cascading concatenation
    CString s1 = temp + AppPath() + _T("\\RegAsm.exe") + _T('"');        // Cascading concatenation
    CString s2 = _T(" /codebase");
    CString message = s1 + _T('"')+ _T(' ')+ _T('"') + AppPath() + _T("\\dv.dll") + _T('"') +_T(' ') +   _T("/tlb:")+('"') + AppPath() + _T("\\dv.tlb") + _T('"')+  s2; 
    CString message1 = _T('"') + AppPath() + _T("\\dv.dll") + _T('"') +_T(' ') +   _T("/tlb:")+('"') + AppPath() + _T("\\dv.tlb") + _T('"')+  s2;

    SHELLEXECUTEINFO ExecuteInfo;
   
    memset(&ExecuteInfo, 0, sizeof(ExecuteInfo));
   
    ExecuteInfo.cbSize       = sizeof(ExecuteInfo);
    ExecuteInfo.fMask        = 0;               
    ExecuteInfo.hwnd         = 0;               
    ExecuteInfo.lpVerb       = L"runas";                      // Operation to perform
    ExecuteInfo.lpFile       = s1;
    ExecuteInfo.lpParameters = message1;                        // Additional parameters
    ExecuteInfo.lpDirectory  = 0;                           // Default directory
    ExecuteInfo.nShow        = SW_HIDE;
    //ExecuteInfo.nShow        = SW_SHOW;
    ExecuteInfo.hInstApp     = 0;
   
    if(ShellExecuteEx(&ExecuteInfo) == FALSE)
    {
        return false;
    }

    return true;
}
bool ExtractDll(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename)
{
   
    TCHAR  sResName[5]  = _T("#101");
    TCHAR sRestype[4] = _T("DLL");
       
   
    HRSRC hres = FindResource(AfxGetResourceHandle(), sResName,sRestype);
   
     
       if (hres == 0)
       {
        return false;       
       }

    HGLOBAL    hbytes = LoadResource(hInstance, hres);
  
       
        // Lock the resource

    LPVOID pdata = LockResource(hbytes);
 

    DWORD dwSize = SizeofResource(hInstance, hres); 
 
       
    HANDLE hFile = CreateFile(szOutputFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  
    /// INSERT DATA IN FILE
    HANDLE hFilemap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);  
 
    LPVOID lpBaseAddress = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);    
  

  
    try
    {
          RtlCopyMemory(lpBaseAddress,pdata,dwSize);
    }
    catch ( ... )
    {
        return false;
       }

    UnmapViewOfFile(lpBaseAddress);
  
    CloseHandle(hFilemap);          
 
    CloseHandle(hFile);  
   
    return true    ;
}
bool ExtractExe(const HINSTANCE hInstance, WORD resourceID, LPCTSTR szOutputFilename)
{
    /*LPTSTR sArgv = argv[1];
     LPTSTR sArgv2 = argv[2];*/

    TCHAR  sResName[5]  = _T("#102");
    TCHAR sRestype[4] = _T("EXE");

    //HINSTANCE Nl=AfxGetInstanceHandle();

    HRSRC hres = FindResource(AfxGetResourceHandle(), sResName, sRestype);
     
       if (hres == 0)
       {
          return false;
        }


    HGLOBAL    hbytes = LoadResource(hInstance, hres);
           
        // Lock the resource

    LPVOID pdata = LockResource(hbytes);
   

    DWORD dwSize = SizeofResource(hInstance, hres); 
       
    HANDLE hFile = CreateFile(szOutputFilename, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  
    /// INSERT DATA IN FILE
    HANDLE hFilemap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, dwSize, NULL);  
 

    LPVOID lpBaseAddress = MapViewOfFile(hFilemap, FILE_MAP_WRITE, 0, 0, 0);    
  
 
    try
    {
            RtlCopyMemory(lpBaseAddress,pdata,dwSize);
    }
    catch ( ... )
    {
        return false;
    }

    UnmapViewOfFile(lpBaseAddress);
   
    CloseHandle(hFilemap);          
  
    CloseHandle(hFile);  
   
  
    return true;
}

This is the MFC code from which I solved my issue. This code is embed the resources, extract that resources and run time register type library.

Thanks

Ankit

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.