This question already has answers here:
Optional Argument of COM Add-in vs Automation Add-in Written in C#
(2 answers)
Closed 4 years ago.
I am working on some VBA COM Add-in and Excel Add-in, whose core codes are written in C#. I'd like to set an optional argument for the function and I know that this is legal for both C# and VBA, and even Excel WorksheetFunction. But I find that finally only Excel functions work well but VBA function always says type mismatch after the library has been registered in both COM Add-in and Excel Add-in.
Here is a simple example: in C# we have some function called
double NormalCDF(double x, double mu = 0, double sigma = 1);
In Excel spreadsheet, I can successfully call
NormalCDF(1.2, 2, 3)
or
NormalCDF(1.2)
Both give the right results. But in VBA, the following is successful,
TestObj.NormalCDF(1.2, 2, 3)
is good, while
TestObj.NormalCDF(1.2)
is failed with "Type mismatch".
Could anyone help with this problem?
////////////////////////////////////////////////////////////////////////////
08/10/2018 Update
Please see a simplified example code:
In "MyLibraryExcel.cs" I have
...
public interface IWorksheetFunctions
{
int test(int a = 1, int b = 1);
}
...
public class WorksheetFunctions : MoodysMathUdfBase,IWorksheetFunctions, IDTExtensibility2
{
protected Application ExcelApplication { get; set; }
public int test(int a = 1, int b = 1)
{
return a + b;
}
}
In "MyLibraryVBA.cs" I have
...
public interface IExcelVBA
{
int test(int a = 1, int b = 1);
}
...
public class ExcelVBA : IExcelVBA
{
public int test(int a = 1, int b = 1)
{
return a + b;
}
}
After building the projects, both two libraries have been registered. In Excel spreadsheet, I want to call
=test(2,3)
which is expected to return 5, and call
=test()
which is expected to return 2.
In VBA macro, I have some codes
Sub TestVBA()
range("Output1").value=TestObj.test(2,3)
range("Output2").value=TestObj.test()
End Sub
which is expected to get 5 and 2 as well.
The interesting thing is that, if I run the two functions of Excel spreadsheet (click the cells and press Enter), both work fine, then run the two functions of VBA, only the first one works, the second one is failed with "Type Mismatch". However, if I run the VBA first, both two test() work fine, then run the two functions of Excel spreadsheet, only the first one works, the second one will display #Value.
Could you please post your VBA Code?
I have tried with below code and it is working fine
Sub OptionalArgs(firstValue As Double, Optional secindValue As Double = 0)
MsgBox CStr(firstValue)
End Sub
try this:
object missing = System.Reflection.Missing.Value;
TestObj.NormalCDF(1.2, missing , missing);
Related
Good Morning,
Introduction:
My problem is about C# dll and VB6. And it refers to the reason of why I can't see the values of the C# properties, but I can see the same values of those properties in my VB6 project.
Explanation:
I created a dll file and a tlb file from a Windows Form Application with VS19 (Visual Studio 2019).
I moved into Properties -> Application and I changed the "Output type" from "Windows application" to "Class Library". After, I clicked in "Assembly information" and I checked the COM visible voice at the bottom of the window that appeared when I clicked.
After that I moved in "Compilation" and checked the "Interop COM" checkbox at the bottom.
In the end I compile the solution and moved the two files in a Virtual Machine (Win XP 32bit SP3), created with Virtual Box. where there's my application developed in VB6.
In my VB6 project I can set and use properties and method of the .NET dll and I see the values (EOL and EOLs are my .NET classes).
Like this:
Vin_car_11 = Mid$(frmInput.txtVinCode.Text, 11, 1)
Select Case Vin_car_11
Case "2"
EOL.XMLPrdWsUrl = "URL" 'Brescia
Case "5"
EOL.XMLPrdWsUrl = "URL" 'Suzzara
Case "9"
EOL.XMLPrdWsUrl = "URL" 'Bolzano
End Select
EOL.Vin = frmInput.txtVinCode.Text
EOL.Van = frmInput.txtVanCode.Text
returnCode = EOLs.GetXMLFile()
Here the problem:
Why I see the value of "EOL.vin" in VB6, but I can't see the same value in C#?
Here the code of my EOL class:
public class cEOL
{
private string vin;
public string Vin
{
get
{
return this.vin;
}
set
{
this.vin = value;
}
}
}
Here the code of my EOLs class:
public class cEOLs
{
#region DICHIARAZIONI
Vehicle.AuthHeader auth;
cEOL EOL;
string result;
string errorDescr;
#endregion
#region COSTRUTTORE
public cEOLs()
{
EOL = new cEOL();
auth = new Vehicle.AuthHeader();
result = "";
errorDescr = "";
}
#endregion
#region METODO
public int GetXMLFile()
{
//chiave di autenticazione server rilasciato da EHSA (IVECO)
auth.AuthKey = "Key";
var client = new Vehicle.EOLClientsAPI4EXT { Url = EOL.XMLPrdWsUrl };
EOL.ReturnCode = client.GetProductionXML(EOL.Vin, EOL.Van, out result, out errorDescr);
EOL.Result = result;
EOL.ErrorDescr = errorDescr;
return EOL.ReturnCode;
}
#endregion
THANKS IN ADVANCE! I HOPE I WAS CLEAR IN THE EXPLANATION!
I resolved it by myself by simply creating a method that returns a string.
I recall this method in my VB6 project for setting the value of the property.
Here the method:
public string ImpostaVIN(string vin)
{
EOL.Vin = vin;
return EOL.Vin;
}
Here the call in VB6:
EOL.Vin = EOLs.ImpostaVIN(string)
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?
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.
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.
I have a working RtdServer-based automation add-in:
How do I create a real-time Excel automation add-in in C# using RtdServer?.
Creating a VBA wrapper is trivial:
Function RtdWrapper(start)
RtdWrapper = Excel.Application.WorksheetFunction.RTD("StackOverflow.RtdServer.ProgId", "", start)
End Function
This works. I have attempted to create a C# wrapper as follows:
[ClassInterface(ClassInterfaceType.AutoDual)]
public class RtdWrappers
{
private readonly Microsoft.Office.Interop.Excel.Application _application = new Application();
public object Countdown(object startingCount)
{
var start = Convert.ToInt32(startingCount.ToString());
return _application.WorksheetFunction.RTD("StackOverflow.RtdServer.ProgId", string.Empty, start);
}
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("CLSID\\{" + t.GUID.ToString().ToUpper() + "}\\Programmable");
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type t)
{
Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey("CLSID\\{" + t.GUID.ToString().ToUpper() + "}\\Programmable");
}
}
When I enter "=Countdown(150)" into a cell in Excel it shows the initial value of 150 which is returned by ConnectData but never updates. Is there some callback that I should register? Am I instantiating the Application object correctly? What am I missing?
Thanks,
Frank
Indeed, you are not getting hold of the right Application object. One solution is to implement the IDTExtensibility2 interface in your add-in. This interface has an OnConnection method that Excel will call when loading your add-in. In this method you are passed the Application object which you can keep in a local variable for later use.