How to release inprocess COM Server object from Excel VBA - excel

How do you force Excel (2007) VBA to release references to a COM server object?
I have written an inprocess (Single instance DLL) COM Server in Visual Foxpro 9 SP2 which is instantiated from Excel 2007 VBA code on my development machine. Excel seems to be holding a reference to the COM object/dll even though I set it = Nothing. This prevents me from rebuilding the DLL due to a "File access is denied TestCOM.dll" message until I quit Excel which is a pain everytime I want to make a change and test it.
I have boiled the code down to a very simple test setup:
The VFP9 project (TestCOM) has just one .prg file with the following contents
DEFINE CLASS TestClass As Session OLEPUBLIC
ENDDEFINE
The VBA Code is as follows:
Sub Test()
Set objTest = CreateObject("TestCOM.TestClass")
Set objTest = Nothing
End Sub
I have tried removing the reference to the COM server library in the VBA project but this does not make any difference.
I have tried with and without DIMing the object variables and it makes no difference.
I have tried creating a new VFP DLL project but the problem persists.
If I build the VFP application/dll as an INPROCESS/DLL and run the VBA code I get this problem but if I build it as an OUTOFPROCESS/EXE and run the VBA code I do NOT get this problem.
I found a very similar problem in COM Object Cleanup except that my COM Server is written in Visual Foxpro 9 SP2 whereas that relates to C# and the OP has not explained in detail how they resolved the problem so I don't know how to get around it; if that is even possible.

The procedure used to instantiate your COM class from the code in your DLL is that Excel calls the COM library layer to find your implementation using either the ProgID or the ClassID. When you have an inproc server this means it finds a path to your DLL and uses LoadLibrary to load it into your client process and then creates the class factory and calls methods in the DLL. So the end result is that Excel calls LoadLibrary on your DLL and this locks the file until Excel calls FreeLibrary on the handle.
Using COM interfaces you don't have control of this. You call CoCreateInstance() (or from VBA you create the object with New or CreateObject which calls this Win32 API underneath). The implementation of this handles the LoadLibrary and everything else until you get handed an interface pointer to work with. Some applications will periodically call CoFreeUnusedLibraries() to attempt to release loaded COM dlls that are not currently in use. The default class factory implementation maintains a counter of objects created that can be used to determine if a DLL is in use or not - but this is not always reliable as COM class writers may not obey the rules. Exiting Excel obviously releases the lock on the file.
When you create your COM class as an out-of-process server - it lives in a separate executable or DLL whose lifetime is managed differently. Excel no longer holds a lock on the DLL and releasing the COM instance may well allow the hosting process to exit.
You can convert a DLL to be used as a localserver (out-of-process) by arranging to have it hosted by DllHost. If you use the OleView utility and find your classes ProgId then you can enable hosting in a surrogate process (dllhost). It's been a while since I did that but there should be information on the web about using surrogate hosting. Obviously hosting a COM object out-of-process makes everything slower and introduces the potential for various marshalling issues. Provided you keep oleautomation compatible interfaces it should be fine.

Adding a shorter answer ....
Releasing the DLL is knotty problem and one familiar to developers of in process COM components for use in Excel.
There are two conditions that need to be satisfied
1) Do not use an early binding library references (Tools->Reference) , use late binding instead. Early binding tools reference will hold a lock.
2) Call CoFreeUnusedLibraries to unload COM servers which no longer have clients.
From your sample code you are already late binding but please check your references. Whilst point 2) is referred to in payyhoyts answer no code is given.
Here is a copy and pasteable declaration
Private Declare Sub CoFreeUnusedLibraries Lib "ole32.dll" ()

Related

Which type library hosts stdDataFormat?

I am trying to import VB6's VBRUN type library into a Visual C++ 2017 header file, but it is failing due to a missing dependency.
Visual C++ reports
"error C4772: #import referenced a type from a missing type library;
'missing_type' used as a placeholder"
Viewing the file with OLE View reveals the problem is with the DataFormat property (DataFormat([out, retval] --<GetRefTypeInfo failed>** Return)).
The missing dependency would appear to be stdDataFormat: which type library does stdDataFormat reside in and why is it missing? (My operating system is Windows 10 Enterprise, 21H1.) Did I miss a selection when installing Visual Studio 6?
This addresses the first part of the question, how to find the typelib (TLB) containing a given interface or class.
Assuming you have no preconception about the TLB / DLL hosting a given COM interface or class you can find it by a couple of registry searches, assuming the type in question actually has been registered.
I started off in HKEY_CLASSES_ROOT with a search for data values = stdDataFormat. This lead to:
[HKEY_CLASSES_ROOT\MSSTDFMT.StdDataFormat]
#="StdDataFormat Object"
[HKEY_CLASSES_ROOT\MSSTDFMT.StdDataFormat\CLSID]
#="{6D835690-900B-11D0-9484-00A0C91110ED}"
Now armed with the CLSID GUID of 6D835690-900B-11D0-9484-00A0C91110ED, search for that value, finding:
HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{6D835690-900B-11D0-9484-00A0C91110ED
of which its important sub-element for our purposes is:
[HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{6D835690-900B-11D0-9484-00A0C91110ED}\InprocServer32]
#="c:\\windows\\SysWow64\\msstdfmt.dll"
...
The InprocServer32 value was the main thing I wanted to find; it tells you the DLL - which is c:\windows\SysWow64\msstdfmt.dll (on my PC - but this should be typical).
Opening msstdfmt.dll in OLEView (or OLEViewDotNet) confirms this; the decompiled IDL from the TLB in that DLL contains:
[
uuid(6D835690-900B-11D0-9484-00A0C91110ED),
helpstring("StdDataFormat Object"),
helpcontext(0x00066b5f)
]
coclass StdDataFormat {
[default] interface IStdDataFormatDisp;
[default, source] dispinterface IStdDataFormatEvents;
};
So msstdfmt.dll should be the missing dependency.
If you did suspect this DLL to begin with, then obviously its a lot quicker to just load it in OLEView and check. But in many cases that won't be obvious when you're starting out.
As for the second part of the question - why is this dependency missing - maybe it would help if you added the relevant section of your code / includes?

Did something change in Visual Studio 2015 IDL or MFC Macro compilation as they relate to the resulting COM Interfaces and registration?

We build an OCX that contains a Map control and many supporting classes (e.g. GeoProjection, Extents) which can act as standalone classes and many of which are also Properties of the Map.
One of our legacy applications that uses the OCX is built in Visual Basic 6. After updating the build from VS2013 to VS2015, we noticed differences in how we have to access some of the properties from VB6. The two in particular that we had problems with were the Map.GeoProjection and the Map.Extents properties. They both started raising "Library Not Registered" errors when attempting to use them.
In the case of the GeoProjection, I was able to resolve the problem simply by adding the VB 'Set' command to the assignment, as follows:
Dim gp As New GeoProjection
gp.ImportFromEPSG m_MapProjection ' contains the EPSG code
Set Map.GeoProjection = gp.Clone
Why the 'Set' wasn't required before this, I don't know. It seems like it should have been since it is setting an object reference.
Even so, when I tried to do the same with the Extents property, it did not resolve the problem, but instead resulted in an "Automation Error". So I next went to review the IDL and MFC macro definitions to see how the definitions differed and why the behavior might differ.
The GeoProjection IDL
[id(192)] IGeoProjection* GeoProjection;
end the Extents IDL
[id(17), propput, nonbrowsable] void Extents(IExtents* nNewValue);
[id(17), propget, nonbrowsable] IExtents* Extents();
The GeoProjection dispatch macro
DISP_PROPERTY_EX_ID(CMapView, "Projection", dispidProjection, GetGeoProjection, SetGeoProjection, VT_DISPATCH)
and the Extents dispatch macro
DISP_PROPERTY_EX(CMapView, "Extents", GetExtents, SetExtents, VT_DISPATCH)
What particularly struck me was the difference in using the DISP_PROPERTY_EX vs the DISP_PROPERTY_EX_ID. Ironically, I can find no Microsoft Documentation on DISP_PROPERTY_EX_ID. The only guidance I could find were comments in the afxdisp.h file, where it describes the two groups of macros, as follows:
on line 288, prior to the macros without the _ID suffix
// these DISP_ macros cause the framework to generate the DISPID
and on line 313, prior to the _ID suffixed macros
// these DISP_ macros allow the app to determine the DISPID
Since we have an .h file that defines dispatch IDs for every function, it seems that we should always use those IDs within the macros, as follows. This assures that the Dispatch IDs will always be the same (which I think would matter when using early-bound COM calls).
DISP_PROPERTY_EX_ID(CMapView, "Extents", dispidExtents, GetExtents, SetExtents, VT_DISPATCH)
Once I made changes to the Extents property in the IDL
[id(17)] IExtents* Extents;
and in the use of the DISP_PROPERTY_EX_ID macro, we were able to successfully set the Extents property from VB6 using the 'Set' statement.
In summary, I don't really know
why the behavior changed in the first place (from VS2013 to VS2015)?
why my changes made things start working again (I have my theories)?
what is the recommended methodology going forward?
a. IDL syntax allows for property definition without having to specify propput and propget. Is one syntax recommended over the other?
b. should I change all of our macros to use the _ID suffixed macro?
Any insight is appreciated.
Thank you.

Call matlab shared library from dotnet core on linux

I am trying to call a shared library created with MathWorks MATLAB Compiler SDK from C# (.NET Core) running on a Linux container.
I have a matlab .m file that I've compiled into a .dll using the MATLAB R2018b compiler SDK. Because the final execution environment is .NET Core 2.2 running on a Linux container I chose the "C Shared Library" option. I call that shared library using the DLLImport mechanism of .NET.
Here is some code from my project. This code is KISS-level because I need to understand how to integrate MATLAB and C# on Linux before I start on the main project.
haveSomePi.m
function hal = haveSomePi()
hal = 3.1415;
end
MyMath.h
extern LIB_MyMath_C_API bool MW_CALL_CONV mlfHaveSomePi(int nargout, mxArray** hal);
MyMathWrapper.cs
[DllImport("MyMath.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void mlfHaveSomePi(int nargout, ref IntPtr hal);
MyMathWrapperTests.cs
[TestMethod]
public void ShouldReturnPi()
{
var hal = IntPtr.Zero;
MyMathWrapper.mlfHaveSomePi(1, ref hal);
double result = (double)hal;
Assert.AreEqual(3.1415, result, 1e-5);
}
The expected result is that the assert in the test method passes. It fails because trying to cast an IntPtr to a double doesn't make sense in this context. I'm sure there is a way to de-reference the IntPtr to get at the underlying double, I just haven't found that particular nugget of information.
I have been successful when compiling the .m file into a .NET library and into a COM object. I don't think I can use either of those libraries on Linux because of differences in the binary load/link format for each OS. When calling the method in the COM object I was able to directly cast the IntPtr to a double, there must be some marshaling magic going on in the background.
Is the method signature for the DLLImport statement correct? Do I map mxArray** to IntPtr?
How do I get the double from the IntPtr? Copy a block of memory into a managed byte array and cast?
My ultimate goal is to access a large signal processing library of matlab code from dotnet. The matlab code uses a lot of vectors and arrays so getting those into and out of the unmangaged library is my next hurdle.
Best regards.
I'm not a mathlab user, so I might be wrong, very wrong!
Getting Linux .dll equivalent
What you need, is the correct shared library/object for the run-time OS to be exported from mathlab.
Windows: .dll = Dynamic Link Library
Linux: .so = shared object [.net core butter and bread for Linux]
Instruction to get .so exported lib from mathlab
Compile your MATLAB files into a shared library (on UNIX)
mcc -t -L C -W MyMath-T link:lib haveSomePi.m libmmfile.mlib
Resulting MyMath.so, MyMath.exports, MyMath.h and MyMath.mlib, more details here
Binding Assembly
Make sure you have MyMath.so file next to MyMath.dll file, (bin, app data or where is needed)
Custom "NativeLibraryLoader" can be used to load different shared lib files based on OS, written by a GIT user because .net core din't had any (link). I would say is a bit over-complicated, but is your choice.
[DllImport] can be used instead!
DllImport without extension, supported on Windows and Linux and MAC will import the appropriate library for the target platform.
[DllImport("MyMath")]
Use <dllmap/> to map an import library name to the target platform library name. For MyMath.dll the corresponding Linux .so should be MyMath.so (more here)
[DllImport("MyMath.dll")]
Config map in csproj
<configuration>
<dllmap dll="MyMath.dll" target="MyMath.so" />
</configuration>
I think the main concern here is that you are doing
C Shared Library
Which is NOT C#...
Instead you should be doing
.NET Assembly
https://in.mathworks.com/help/compiler_sdk/gs/create-a-dotnet-application-with-matlab-code.html
It's important to note that .NET Core is not supported either, and you will have to change your project to a "classic" .NET Framework (If I recall correctly, at least 4.x)

How to create a COM visible dll in F#

My aim is to create a COM Visible Type that can be imported into VBA (Excel) and consumed there.
The Excel Object Browser can see my class but not any public methods of the class and fails on the attempt at calling a public method.
My F# Code:
namespace DotNetLibrary
type public Class1() =
member public this.DotNetMethod (x:string) = "Hello" + x
In the AssemblyInfo.fs I also amend to [<assembly: ComVisible(true)>]
I run regasm with switches of /codebase /tlb and a .tlb file is generated.
VBA finds my library in the references browser but does not pick up the DotNetMethod defined on Class1 above.
I have tried to follow the C# guidance for this topic in getting to where I am at the moment but I'm not getting to the finish line.
Run-Time Errors
The reason that VBA could not run the method succesfully is because I used the 32-bit version of the regasm utility instead of the 64-bit version to register the type library for COM. Given that I am using 64-bit Excel it needed 64-bit COM type libraries.
Compile-Time Issues
The reason that VBA could not identify the methods in the IDE could be related to the above, but is also likely to be due to the interface issues raised by
#HansPassant in his comments above.

Can you use assembly.load in monotouch?

I'm currently trying to load a plugin assembly dynamically in a monotouch app.
To do this, I'm referencing the plugin dll in my app project, setting the limker to 'sdk only' and then i'm trying to call Assembly.Load(filename) within my app when the plugin is required.
This is the same approach that I've previously successfully used in monodroid. However currently, this is failing in monotouch with a FileLoadException.
Is this approach possible in monotouch? Is there a special file path you need to include? Or is this not supported in the aot environment?
Note: Obviously there are other ways I can achieve a similar effect - and I do have a backup plan... but this is my preferred route (if I can make it work)
Code like:
var a = Assembly.Load ("mscorlib.dll");
Assert.NotNull (a);
works fine with both the simulator and devices. However the parameter for Load is assemblyString which is not a filename (even if the exception thrown make you think it is).
Many other overloads exists (for Load) and other methods too (e.g. LoadFrom) but they might not all work inside MonoTouch (since some runtime support might be missing).
NOTE
Handling of mscorlib.dll is special (and works in more cases than other assembles, i.e. shortcuts). However the reflection-based methods seems to work as expected in more cases, e.g.:
string filename = System.IO.Path.GetFileName (GetType ().Assembly.Location);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom (filename);
Assembly.Load (or any other way of loading code dynamically) is not supported in MonoTouch.
This is an iOS restriction - all the executable code has to be in the app (and it has to be native code, which is why we use AOT to generate native code at compile time).

Resources