Casting COM types in C++ - c#

I have the following COM types: Project, ContainerItem and Node.
Project has a collection property with an Append function that accepts ContainerItems.
In C#, using type libraries I can send a Node object to the Append function and the library works as expected:
var prj = new Project();
var node = new Node();
prj.collection.Append(node);
In C++ I tried a direct pointer cast expecting this is what C# was doing, but it ends up in an error:
ProjectPtr prj;
prj.CreateInstance(__uuidof(Project));
NodePtr node;
node.CreateInstance(__uuidof(Node));
prj->collection->Append((ContainerItem**)&node.GetInterfacePtr());
Is there a specific way to these type of COM pointer casts in C++? What am I missing?

COM casting is done with the QueryInterface() method. The object is queried for its support of the interface (based on the GUID), and if the interface is supported, the internal reference counter is incremented (see AddRef()) and a pointer to the interface is returned. MSDN has more detail on the inner workings.
C++ does not directly support the code generation for the "COM cast" as C# does, but its implementation is simple enough.
struct bad_com_cast : std::runtime_error {
bad_com_cast() : std::runtime_error("COM interface not supported") {}
};
template <class To, class From>
To* qi_cast(From* iunknown)
{
HRESULT hr = S_OK;
To* ptr = NULL;
if (iunknown) {
hr = iunknown->QueryInterface(__uuidof(To), (void**)(&ptr));
if (hr != S_OK) {
throw bad_com_cast(); // or return NULL
}
}
return ptr;
}
Using the above "cast", the sample can be implemented as follows;
ContainerItem* ci = qi_cast<ContainerItem>(node);
prj->collection->Append(&ci);
If the ATL library is being used, you can use ATL::CComQIPtr<> directly to obtain the equivalent semantics;
auto ci = CComQIPtr<ContainerItem>(node);
if (ci) {
// ...
}

Just like #HansPassant commented, I had to use the QueryInterface function:
ContainerItem* ci = nullptr;
node.QueryInterface(__uuidof(ContainerItem), ci);
prj->collection->Append(&ci);

Related

WCF Generated Classes

I'm converting a sample VB Client (from a 3rd party SDK which consumes its WCF Services) to C#. The client in VB when executed, works correctly.
I'm writing a small wrapper in C# Windows Form in vs2015 to consume the same WCF Services. I was able to add the service references in VS2015.
I am having a problem making an equivalent call in VB which works but for some reason in C#, it does not work, as if the generated C# classes is incorrect.
in the working sample VB,
I have a call ContinueGetList
Dim siteList() As SRAdminSys.MW_DataContractCommon
Dim iRecCount As Integer = 20
Dim Status As SRAdminSys.MW_ContinueStatusEnum
Status = m_wcfSysDB.ContinueGetList(iRecCount, siteList)
The call returns a list in siteList which is an array of SRAdminSys.MW_DataContractCommon
note: I think* the actual The array returned by the webservice , is of type MW_Site which inherits DataContractCommon - (* when I made the same call in a C# equivalent call, I get an error and when I checked the error , it mentioned that it is casting MW_Site to MW_DataContractCommon )- See further test below.
Partial Public Class MW_Site
Inherits SRAdminSys.MW_DataContractCommon
The Reference.vb from the Generated Proxy Class:
Public Function ContinueGetList(ByVal iCount As Integer, ByRef list() As SRAdminSys.MW_DataContractCommon) As Integer Implements SRAdminSys.IMW_KWSAdminSysDatabase.ContinueGetList
Return MyBase.Channel.ContinueGetList(iCount, list)
End Function
Now in the Non-Working prototype in C# ( it does compile though ) ,
int[] lst_SiteIds = new int[] { };
int iRecCount = 20;
SRAdminSys.MW_ContinueStatusEnum status;
status = (SRAdminSys.MW_ContinueStatusEnum)adminSysClient.ContinueGetList(iRecCount,ref siteList);
The return value status indicated that the call failed and when I check the error - a WCF method GetLastError(), I get
Unable to cast object of type 'MW_DataContractCommon[]' to type 'MW_Site[]'.
When I check the MW_Site Partial class generated by C# Service Reference, I notice it inherits DataContractCommon, so I expected it to work:
public partial class MW_Site : SRAdminSys.MW_DataContractCommon {
Reference.cs
public int ContinueGetList(int iCount, ref TestUtil.SRAdminSys.MW_DataContractCommon[] list) {
TestUtil.SRAdminSys.ContinueGetListRequest inValue = new TestUtil.SRAdminSys.ContinueGetListRequest();
inValue.iCount = iCount;
inValue.list = list;
TestUtil.SRAdminSys.ContinueGetListResponse retVal = ((TestUtil.SRAdminSys.IMW_KWSAdminSysDatabase)(this)).ContinueGetList(inValue);
list = retVal.list;
return retVal.ContinueGetListResult;
}
CWUtility.SRAdminSys.ContinueGetListResponse retVal = ((CWUtility.SRAdminSys.IMW_KWSAdminSysDatabase)(this)).ContinueGetList(inValue);
list = retVal.list;
return retVal.ContinueGetListResult;
}
In relation to the partial class and inheritance of DataContractCommon - On another sample code which works in VB but not in C# when both is pointing to the same WCF service. The only difference is a VB App vs a C# App which points to their respective generated proxy classes from VS Service Reference.
Dim sitekey__ As New SRAdminSite.MW_Key
bRet = m_wcfSiteDB.Add(1, eKEY_COLLECTION, sitekey__)
VB, Reference.vb
Public Function Add(ByVal iSiteID As Integer, ByVal iCollectionType As Integer, ByRef iRecord As SRAdminSite.MW_DataContractCommon) As Boolean Implements SRAdminSite.IMW_KWSAdminSiteDatabase.Add
Return MyBase.Channel.Add(iSiteID, iCollectionType, iRecord)
End Function
SRAdminSite.MW_Key sitekey__ = new SRAdminSite.MW_Key();
//COMPILE ERROR on sitekey__ although MW_Key is a partial class which inherits MW_DataContractCommon
bRet = adminSiteClient.Add(1, (int)SRAdminSite.MW_SiteCollectionTypesEnum.eKEY_COLLECTION, ref sitekey__);
C#, Reference.cs
public bool Add(int iSiteID, int iCollectionType, ref SRAdminSite.MW_DataContractCommon iRecord)
{
SRAdminSite.AddRequest inValue = new SRAdminSite.AddRequest();
inValue.iSiteID = iSiteID;
inValue.iCollectionType = iCollectionType;
inValue.iRecord = iRecord;
SRAdminSite.AddResponse retVal = ((SRAdminSite.IMW_KWSAdminSiteDatabase)(this)).Add(inValue);
iRecord = retVal.iRecord;
return retVal.AddResult;
}
So both these examples seems to be related to the way the proxy classes the WCF Service was generated and inheriting other classes but unable to work. In the 2nd sample the error was at compile time...
Can anyone shed some light, why in VB the default generated class works when called, but in c#, the same equivalent call to the same method does not work?
I've consumed other 3rd party WCF services and normally, importing the Service Reference and consuming the methods were a breeze...
For some reason, this one, I cant wrap my head around why it will not work. Is there something I'm missing or need to modify in the way the Reference.cs is generated before I consume them?

C# : Get COM object from the Running Object Table

I'm working a project that uses API from a third party COM Server. The COM Server is a local server (out of process exe) on which I have no control.
I'm trying to access COM objects from the runnin object table to choose between the several instances of COM objects started with each instance of the application :
private static List<object> GetRunningInstances(string progId) {
// get Running Object Table ...
IRunningObjectTable Rot = null;
GetRunningObjectTable(0, out Rot);
if (Rot == null)
return null;
// get enumerator for ROT entries
IEnumMoniker monikerEnumerator = null;
Rot.EnumRunning(out monikerEnumerator);
if (monikerEnumerator == null) return null;
monikerEnumerator.Reset();
List<object> instances = new List<object>();
IntPtr pNumFetched = new IntPtr();
IMoniker[] monikers = new IMoniker[1];
while (monikerEnumerator.Next(1, monikers, pNumFetched) == 0) {
IBindCtx bindCtx;
CreateBindCtx(0, out bindCtx);
if (bindCtx == null) continue;
Guid clsid = Type.GetTypeFromProgID(progId).GUID;
string displayName;
Guid monikerClsid;
Guid riid = Marshal.GenerateGuidForType(typeof(IApplication));
object obj;
monikers[0].GetDisplayName(bindCtx, null, out displayName);
monikers[0].GetClassID(out monikerClsid);
if (displayName.IndexOf(clsid.ToString(), StringComparison.OrdinalIgnoreCase) > 0) {
//monikers[0].BindToObject(bindCtx, null, ref unkid, out obj);
Rot.GetObject(monikers[0], out obj);
instances.Add((IApplication)obj);
}
}
}
If I start two instances of the target application, the ROT dump shows two instances of the corresponding COM object (named IApplication here) as GetDisplayName shows the right clsid for the interface IApplication registered in the registry.
The problem is that the objects I get from Rot.GetObject are described as System.__ComObject and cannot be cast to IApplication (InvalidCastException because QueryInterface failed with E_NOINTERFACE) even if their moniker describe the right clsid...
I tried casting it progammatically to every available type in my project just to see but the only success is casting it to System.__ComObject...
I also tried using IMoniker.BindToObject instead of Rot.GetObject but this time, I get a FileNotFound Exception when I provide the corresponding interface GUID. BindToObject works when I provide the riid for IUnknown but it gives me a System.__ComObject I can't cast (back to square one !).
For information, in the ROT dump, I can also shows a file moniker corresponding to an open project in the target app but I cannot create a COM object from this either.
Anyone has an idea about how to correctly retrieve the objects from the ROT ?
Thanks,
Regards.
EDIT :
After a few days out and a new eye on this problem, I discovered the CLSID in the moniker's display name is not the exact same one I want but has two digits off (the indexof test turns out to be wrong).
After carefully reading the clsid's it turns out that the clsid in the moniker's displayname is the clsid of the coclass of IApplication and not the clsid of IApplication.
I tried casting the object to "ApplicationClass" (the aforedmentionned coclass) but this gives me an exception. The additional info I get (in french) could translate as follows : Impossible to cast __ComObject wrapper instances to another class but it's possible to cast these instances to interfaces as long as the underlying com component supports QueryInterface calls for the interface IID.
Any idea on how to proceed from here ?
I don't now if you still have a problem but since there is no answer yet I want to share what I've done after couple of weeks research about handling multiple COM Interfaces on ROT.
I've fetched all the objects from ROT and store them in hashtable to ensure uniqueness via Key/Value but you can adjust it to a List as you prefer on question. You just need to fetch running object value to add your List.
public static Hashtable GetRunningObjectTable()
{
Hashtable result = new Hashtable();
IntPtr numFetched = new IntPtr();
IRunningObjectTable runningObjectTable;
IEnumMoniker monikerEnumerator;
IMoniker[] monikers = new IMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
IBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out runningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
After that you can cast the object stored in your List to your COM Interface. For instance, I've also shared my way which works for Rhapsody COM Interface in below;
Hashtable runningObjects = GetRunningObjectTable();
IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator();
while (rotEnumerator.MoveNext())
{
string candidateName = (string)rotEnumerator.Key;
if (!candidateName.StartsWith("Rhapsody"))
continue;
rhapsody.RPApplication app = rotEnumerator.Value as rhapsody.RPApplication;
if (app == null)
continue;
// Do your stuff app (com object) in here..
}

C# Namespace not found for DLL

Ok, I will preface this by saying I did do a look up and read a lot of similar questions and answers on here before posting this.
Background Info
Using Visual Studio Professional 2013
Goal:
This project is for my own amusement and to try to learn as much as I can.
I have a native C++ header file called BinaryTree.h which is just a simple data structure that uses recursive logic to build a binary search tree. It works quite well on its own.
I want to build a GUI in C# that uses this. (Its not really useful or practical, I just choose it, well because I wanted to. Also, while the logic inside the binary tree class is complex(ish), I only need to call 2 methods, a addNode method, and a toString method which return the max depth and number of nodes).
I choose using a c++/cli wrapper to accomplish this. Everything seemed to go well, the build was successful and a .dll file was created in the debug directory of my project.
Now, I started in on the C# side of things. I added the .dll file to references. However, when I typed in " using filename.dll;" I got an error saying "Type or namespace not found...".
To reiterate I did some researching. I found (it seemed in VS2010) that different target frameworks could cause this error. I checked mine, targets for both were net4.5, so that is not the problem.
Here is the code from my c++/cli wrapper. Perhaps it has something to do with using templates? Any help is appreciated.
#pragma once
#include "D:\Schoolwork 2015\Test Projects\CPPtoC#WrapperTest\CPPLogic\CPPLogic\BinaryTree.h"
using namespace System;
namespace BinaryTreeWrapper {
template<class Data>
public ref class BinaryTreeWrapperClass
{
public:
BinaryTreeWrapperClass(){ tree = new BinaryTree(); }
~BinaryTreeWrapperClass(){ this->!BinaryTreeWrapperClass(); }
!BinaryTreeWrapperClass(){ delete tree; }
//methods
void wrapperAddNode(Data)
{
tree->addNode(Data);
}
std::string wrapperToString()
{
return tree->toString();
}
private:
BinaryTree* tree;
};
}
Screenshot of the error:
EDIT
Ok, so here is a weird thing... my original file built just fine with the new code and produced a .dll file. However, I decided to try a fresh project since the namespace was still not being found. Upon moving the code over and trying to build, I've run into 4 errors:
Error 1 error C2955: 'BinaryTree' : use of class template requires template argument list
Error 2 error C2512: 'BinaryTree' : no appropriate default constructor available
Error 3 error C2662: 'void BinaryTree::addNode(Data)' : cannot convert 'this' pointer from 'BinaryTree' to 'BinaryTree &'
Error 4 error C2662: 'std::string BinaryTree::toString(void) const' : cannot convert 'this' pointer from 'BinaryTree' to 'const BinaryTree &'
I copied the code exactly, only changing the namespace to "TreeWrapper' and the class name to 'TreeWrapperClass'.
To help, I've include a snippet from my BinaryTree.h file. There is a bunch more that defines the 'NODE' class, but I didn't want to clutter it up more than i needed.
After further investigation, it appears the problem lies with using 'generic'. If I switch it all to 'template' it builds just fine, but then it can't be used as a reference in C# (getting the namespace error). I built a test project using very simple methods (no templates) and was able to use the .dll wrapper I made in C#. So the problem lies with templates and generics.
Last Edit
I've found if I change the code to initiate the template as 'int' it works just fine, and I can use it in C#. For example:
...
BinaryTreeWrapperClass(){ tree = new BinaryTree<int>(); }
....
private:
BinaryTree<int>* tree;
BinaryTree.h
template<class Data>
class BinaryTree
{
private:
Node<Data>* root;
unsigned int nNodes;
unsigned int maxDepth;
unsigned int currentDepth;
void traverse(Node<Data>*& node, Data data);
public:
BinaryTree();
~BinaryTree();
void addNode(Data);
std::string toString() const
{
std::stringstream sstrm;
sstrm << "\n\t"
<< "Max Depth: " << maxDepth << "\n"
<< "Number of Nodes: " << nNodes << "\n";
return sstrm.str(); // convert the stringstream to a string
}
};
template<class Data>
BinaryTree<Data>::BinaryTree() //constructor
{
//this->root = NULL;
this->root = new Node<Data>(); //we want root to point to a null node.
maxDepth = 0;
nNodes = 0;
}
template<class Data>
BinaryTree<Data>::~BinaryTree() //destructor
{
}
template<class Data>
void BinaryTree<Data>::addNode(Data data)
{
traverse(root, data); //call traverse to get to the node
//set currentDepth to 0
currentDepth = 0;
}
template<class Data>
void BinaryTree<Data>::traverse(Node<Data>*& node, Data data)
{
//increment current depth
currentDepth++;
if (node == NULL) //adds new node with data
{
node = new Node<Data>(data);
//increment nNode
nNodes++;
//increment maxDepth if current depth is greater
if (maxDepth < currentDepth)
{
maxDepth = currentDepth - 1; //currentDepth counts root as 1, even though its 0;
}
return;
}
else if (node->getData() >= data) //case for left, getData must be bigger. The rule is, if a number is equal to getData or greater, it is added to the left node
{
Node<Data>* temp = node->getLeftNode();
traverse(temp, data); //recursive call, going down left side of tree
node->setLeftNode(temp);
}
else if (node->getData() < data) //case for right, getData must be less
{
Node<Data>* temp = node->getRightNode();
traverse(temp, data);
node->setRightNode(temp);
}
return;
}
You're declaring a template, but are not actually instantiating it. C++/CLI templates are just like C++ templates - if you don't instantiate them, they just don't exist outside of the compilation unit.
You're looking for generics here (yes, C++/CLI has both templates and generics). And here's how you declare a generic in C++/CLI:
generic<class Data>
public ref class BinaryTreeWrapperClass
{
// ...
}
But you'll get stuck at this point for several reasons.
First, I'll include the parts which are OK:
generic<class Data>
public ref class BinaryTreeWrapperClass
{
public:
BinaryTreeWrapperClass(){ tree = new BinaryTree(); }
~BinaryTreeWrapperClass(){ this->!BinaryTreeWrapperClass(); }
!BinaryTreeWrapperClass(){ delete tree; }
private:
BinaryTree* tree;
};
You've got this right.
Next, let's look at:
std::string wrapperToString()
{
return tree->toString();
}
That's no good, since you're returning an std::string - you don't want to use that from C#, so let's return a System::String^ instead (using marshal_as):
#include <msclr/marshal_cppstd.h>
System::String^ wrapperToString()
{
return msclr::interop::marshal_as<System::String^>(tree->toString());
}
Here, that's much better for use in C#.
And finally, there's this:
void wrapperAddNode(Data)
{
tree->addNode(Data);
}
See... here you'll have to do some real interop. You want to pass a managed object to a native one for storage. The GC will get in your way.
The GC is allowed to relocate any managed object (move it to another memory location), but your native code is clueless about this. You'll need to pin the object so that the GC won't move it.
There are several ways to do this, and I don't know what BinaryTree::addNode looks like, but I'll just suppose it's BinaryTree::addNode(void*).
For long-term object pinning, you can use a GCHandle.
The full code looks like this:
generic<class Data>
public ref class BinaryTreeWrapperClass
{
public:
BinaryTreeWrapperClass()
{
tree = new BinaryTree();
nodeHandles = gcnew System::Collections::Generic::List<System::Runtime::InteropServices::GCHandle>();
}
~BinaryTreeWrapperClass(){ this->!BinaryTreeWrapperClass(); }
!BinaryTreeWrapperClass()
{
delete tree;
for each (auto handle in nodeHandles)
handle.Free();
}
void wrapperAddNode(Data data)
{
auto handle = System::Runtime::InteropServices::GCHandle::Alloc(
safe_cast<System::Object^>(data),
System::Runtime::InteropServices::GCHandleType::Pinned);
nodeHandles->Add(handle);
tree->addNode(handle.AddrOfPinnedObject().ToPointer());
}
System::String^ wrapperToString()
{
return msclr::interop::marshal_as<System::String^>(tree->toString());
}
private:
BinaryTree* tree;
System::Collections::Generic::List<System::Runtime::InteropServices::GCHandle>^ nodeHandles;
};
This allocates a GCHandle for each node, and stores it in a list in order to free it later. Freeing a pinned handle releases a reference to the object (so it becomes collectable if nothing else references it) as well as its pinned status.
After digging around I think I found the answer, although not definitively, so if anyone can chime in I would appreciate it. (Apologies in advance for any misuse of vocabulary, but I think I can get the idea across).
It seems the problem lies in the fundamental difference between templates in native C++ and generics. Templates are instantiated at compilation, and are considered a type. They cannot be changed at runtime, whereas generics can. I don't think there is an elegant way to solve that.
At least I accomplished one goal of my project, which was learning as much as I can haha. I was able to get c++/cli wrappers working for things without templates, and if I choose a type for the template before building the .dll (see above)
If anyone else has an idea please let me know.

Passing Structures to unmanaged code from C# DLL to VB6

I have some customers that uses apps using VB6 and some others languages. The code works fine using OLE (COM), but customers prefers to use native DLL to avoid to register the libraries and deploy them in the field.
When I register the DLL and test in VB6 (OLE), it works fine. When I call a method that return a Strutc, it works fine with OLE, but, if I access in VB6 using Declare, I got fatal error in method that should return the same kind of struct (method 'EchoTestData' see bellow).
The code is compile in C# to use in unmanaged code with OLE or by entry points> I had tested with VB6.
namespace TestLib
{
[ClassInterface(ClassInterfaceType.AutoDual)]
[ProgId("TestClass")]
public class TestClass : System.EnterpriseServices.ServicedComponent
{
/*
* NOTE:
* ExportDllAttribut: a library that I have used to publish the Entry Points,
* I had modified that project and it works fine. After complile, the libray
* make the entry points...
* http://www.codeproject.com/Articles/16310/How-to-Automate-Exporting-NET-Function-to-Unmanage
*/
/*
* System.String: Converts to a string terminating in a null
* reference or to a BSTR
*/
StructLayout(LayoutKind.Sequential)]
public struct StructEchoData
{
[MarshalAs(UnmanagedType.BStr)]
public string Str1;
[MarshalAs(UnmanagedType.BStr)]
public string Str2;
}
/*
* Method static: when I use this method, the Vb6 CRASH and the EVENT VIEWER
* show only: System.Runtime.InteropServices.MarshalDirectiveException
* HERE IS THE PROBLEM in VB6 with declare...
* Return: struct of StructEchoData type
*/
[ExportDllAttribute.ExportDll("EchoTestStructure", CallingConvention.StdCall)]
public static StructEchoData EchoTestStructure(string echo1, string echo2)
{
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoTestData] Retorno String[1]: ", echo1),
Str2 = String.Concat("[EchoTestData] Retorno String[1]: ", echo2)
};
return ws;
}
/*
* Method NOT static: it is used as COM (OLE) in VB6
* In VB6 it returns very nice using with COM.
* Note that returns the StructEchoData without problems...
* Return: struct of StructEchoData
*/
[ExportDllAttribute.ExportDll("EchoTestStructureOle", CallingConvention.StdCall)]
public StructEchoData EchoTestStructureOle(string echo1, string echo2)
{
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoOle] Return StringOle[1]: ", echo1),
Str2 = String.Concat("[EchoOle] Return StringOle[2]: ", echo2),
};
return ws;
}
/*
* Method static: It works very nice using 'Declare in VB6'
* Return: single string
*/
[ExportDllAttribute.ExportDll("EchoS", CallingConvention.StdCall)]
// [return: MarshalAs(UnmanagedType.LPStr)]
public static string EchoS(string echo)
{
return "[TestClass::EchoS from TestLib.dll]" + echo;
}
/*
* Method NOT static: it is used as COM (OLE) in VB6
* In VB6 it returns very nice
* Return: single string
*/
[ExportDllAttribute.ExportDll("EchoSOle", CallingConvention.StdCall)]
// [return: MarshalAs(UnmanagedType.LPStr)]
public string EchoSOle(string echo)
{
return "[TestClass::EchoS from TestLib.dll]: " + echo;
}
}
}
Now, in VB6 I cant test using Declare or register the TestLib.Dll as COM
USING DECLARE in VB6:
Private Declare Function EchoS Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll"_
(ByVal echo As String) As String
Private Type StructEchoData
Str1 As String
Str2 As String
End Type
Private Declare Function EchoTestStructure Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll"_
(ByVal echo1 As String, ByVal echo2 As String) As StructEchoData
// ERROR - CRASH VB6
Private Sub EchoData_Click()
Dim ret As StructEchoData
ret = EchoTestStructure("echo1 Vb6", "echo2 vb6")
TextBox.Text = ret.Str1
End Sub
// WORKS Fine, returns a string
Private Sub btRunEchoTestLib_Click()
TextBox.Text = EchoS("{Run from VB6}")
End Sub
And using VB6 wiht OLE:
1St. Registering the DLL: C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe TestLib.dll /tlb:Test.tlb
2nd. Add the reference in project. The program runs and I got the response with one string and receive the response when has a structure too.
Private Sub Echo_Click()
Dim ResStr As String
Dim obj As TestLib.TestClass
Set obj = New TestClass
ResStr = obj.EchoSOle(" Test message")
MsgBox "Msg Echo: " & ResStr, vbInformation, "ResStr"
Beep
End Sub
Private Sub EchoDataOle_Click()
Dim obj As TestLib.TestClass
Set obj = New TestClass
// Here I define the struct and works fine!!
Dim ret As TestLib.StructEchoData
ret = obj.EchoTestStructureOle("test msg1", "test msg2")
TextStr1.Text = ret.Str1
TextStr2.Text = ret.Str2
Debug.Print ret.Str1
Debug.Print ret.Str2
Beep
End Sub
So, the StructEchoData is wrapped fine using COM, but if I want to use Declare and got the access by entry point, not work. Could anybody suggest anything, please?
The VB6 Declare Lib only works for unmanged DLL exported functions. C# does not expose it's functions as unmanged functions, since it's managed code. The only supported way to exporting classes from C# is to use COM. So you can't use Declare Lib to access C# methods from VB6.
There is a library that is supposed to create unmanged exports from your C# code; Robert Giesecke's Unmanaged Exports. I've personally never used it; I've only seen it mentioned on Stack Overflow.
There is a supported way to export unmanged functions from a .Net assembly and that is using C++/CLR since it allows the mixing of managed and unmanged code. You could create a C++/CLR wrapper that exported unmanged functions that call your C# DLL. That is the way I would go.
You cannot create Dynamic Link Libraries with c#.
However, with a little bit of C++ you can create a bootstrapper for .Net dll's by leveraging the CLR hosting API.
CLR Hosting API
You can create a Dynamic Link Library in C++ with a method called something like "LoadPlugins".
Write LoadPlugins to load the CLR (or a specific version of the CLR), then use reflection to load some .net DLL's.
Also with the same C++ code, you can expose .net methods in the C++ dll as exported native functions in c++ that will work with VB6's declare...
Each function in c++ would have to check to make sure the CLR is loaded, and that the .net code being called is loaded, then use reflection to call it.
Thanks for replies,
The C# only will work with unmanaged DLL if there are Entry Points into the code. The declarations that were used into the code with the statement 'ExportDllAttribut' generate the respectives Entry Points that are necessary to be used by unmanagement code.
The problem is to use export with "Data Structure", that is my question.
I had used without problems the methods that return string or integer values, like EchoS in this post. I used this example (TestLib.DLL) with VB6 and it works fine with "Declare" in VB6:
Private Declare Function EchoS Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll"_
(ByVal echo As String) As String
// WORKS Fine, returns a string
Private Sub btRunEchoTestLib_Click()
TextBox.Text = EchoS("{Run from VB6}")
End Sub
I wrote a note at the begining the C# code, but could not be clear, sorry. Explained a bit more. After I compile the library, I use in "Project properties", "Build events" the following command:
"$(ProjectDir)libs\ExportDll.exe" "$(TargetPath)" /Debug
This directive [ExportDllAttribute.ExportDll("NameOfEntryPoint"] disasembly the DLL (using ilasm.exe and ildasm.exe) and write the exports directives to create Entry Points, compiling and generating the DLL again. I used few years and works fine.
If I apply the dumpbin command in DLL, the results are the Entry Points published, so, it is possible to use with unmanaged code like VB6, but using the correct Marshalling type or statement in Vb6. Example:
dumpbin.exe /exports TestLib.dll
ordinal hint RVA name
2 0 0000A70E EchoC
5 1 0000A73E EchoSOle
3 2 0000A71E EchoTestStructure
6 3 0000A74E EchoTestStructureOle
This code was tested using the method EchoS (with Declare) or EchoSOle (COM) and in both cases are fine. When the DLL is used as OLE in app, the structure can be see as Type and the run fine, but, in VB6 with declare, I got error MarshalDirectiveException only with Structure returns, singles types like string C# or integer, I don't have problem.
I think thet the problem is how to the Structure was marshalling by the static method EchoTestStructure or how to was declared in VB6. Maybe could be a wrong way used in VB6 (that I am not any expert) or any marshalling parameter in Static Method 'EchoTestStructure', that is the real question and help.
PS: I will see the links in the replies to try another approaches if I can´t solve it.
Thanks again, Any other idea?
It was Solved, but by another way... this can be not the state of the art, but it works.
First thing, it was needed to change the Marshaling type in struct, from BStr to LPStr.
I don't know what was exactly the motive because some Microsoft helps and others links, they said: "System.String : Converts to a string terminating in a null reference or to a BSTR".
If I set "Hello" into the Str1 in the Structure, I receive "效汬㉯映潲䉖⸶⸮" into the DLL. If I return a fixed string "Hello" form DLL, the VB6 shows only the first char "H", so, I change to ANSI (LPStr) and solve it. Using OLE, the BSTR Works fine, but native DLL does not. The code was changed to:
StructLayout(LayoutKind.Sequential)]
public struct StructEchoData
{
[MarshalAs(UnmanagedType.BStr)]
public string Str1;
[MarshalAs(UnmanagedType.BStr)]
public string Str2;
}
In the method 'EchoTestStructureOle' declaration, it was change to use reference and passing the address of structure intead return a structure. Before the code was:
public StructEchoData EchoTestStructure(string echo1, string echo2)
{
// It Works only wtih OLE the return of the type StructEchoData
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoTestData] Return from DLL String[1]: ", echo1),
Str2 = String.Concat("[EchoTestData] Return from DLL String[2]: ", echo2)
};
return ws;
}
And now I am using interger to return the status (1 ok, -1 error) and the parameter structure type by reference, the method was change to:
public static int EchoTestStructure(ref StructEchoData inOutString)
{
// used to test the return of values only, data 'in' not used
var ws = new StructEchoData
{
Str1 = String.Concat("[EchoTestData] Return from DLL String[1]: ", inOutString.Str1),
Str2 = String.Concat("[EchoTestData] Return from DLL String[2]: ", inOutString.Str2)
};
inOutString = ws;
return 1;
}
With reference, I can receive the values from VB6 and return to VB6 without no problems. I think that must have a way to return a structure, but, this approach solve it for this time.
In VB6 side: the code was changed to:
Private Type StructEchoData // Same type, do not change...
Str1 As String
Str2 As String
End Type
Private Declare Function EchoTestData Lib "C:\Temp\_run.dll\src.app.vb6\TestLib.dll" (ByRef strcData As StructEchoData) As Long
Private Sub ShowMessage_Click()
Dim res As Long
Dim strcData As StructEchoData
strcData.Str1 = "Str1 from VB6..."
strcData.Str2 = "Str2 from VB6..."
res = EchoTestData(strcData)
/*
strcData.Str1 --> Data Received from DLL:
[EchoTestData] Return from DLL String[1]: Str1 from VB6...
strcData.Str2 --> Data Received from DLL
[EchoTestData] Return from DLL String[2]: Str2 from VB6...
*/
...
End Sub
Thanks for the tips for while. If you have any suggest, it will be welcome.

Handling a SAFEARRAY returned from C# server

I need to return an array of structure (classes) from a C# library to an unmanaged C++ client. This is the function in the C# library:
[ComVisible(true)]
[Serializable]
public sealed class RetrieverProxy : IRetrieverProxy
{
public IMyRecord[] RetrieveMyRecords(long[] ids)
{
IList<IMyRecord> result = new List<IMyRecord>();
for (int i = 0; i < ids.Count(); i++)
{
result.Add(new MyRecord()
{
// some test data
});
}
return result.ToArray();
}
}
MyRecord itself contains an array of structures, which are also COM visible and contain a double and a DateTime field.
I get the follow wrapper from regasm:
inline SAFEARRAY * IRetrieverProxy::RetrieveMyRecords (SAFEARRAY * ids) {
SAFEARRAY * _result = 0;
HRESULT _hr = raw_RetrieveMyRecords(ids, &_result);
if (FAILED(_hr)) _com_issue_errorex(_hr, this, __uuidof(this));
return _result;
}
From the client code, I invoke the library like the following:
SAFEARRAY *pMyRecordsSA;
SAFEARRAY *pIds;
// omitting pIds initialization, because from the library I can see
// that they are ok
pMyRecordsSA = pIRetrieverProxy->RetrieveMyRecords(pIds);
The problem I have is how to retrieve the results which are now stored in pMyRecordsSA. I have tried the following but I it's not working:
IMyRecordPtr pIMyRecords(__uuidof(MyRecord));
HRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&pIMyRecords);
but then trying to use the pIMyRecords pointer gives an access violation (hr is 0K).
Any ideas? I am really stuck on this.
It turned out that I just needed "another level of indirection". That is, a pointer to pointer vs a simple pointer.
IMyRecords** pIMyRecords;
HRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&pIMyRecords);
This did the trick.
Take a look at CComSafeArray it might save you some time.

Categories

Resources