microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.
MIT License
2k stars 84 forks source link

Support custom Dll Import search path for entry point functions #1029

Closed youyuanwu closed 10 months ago

youyuanwu commented 10 months ago

The generated code marks the dll import search path to be system32 path. But the dll lives in C:\Program Files\Microsoft Service Fabric\bin\Fabric\Fabric.Code

namespace Microsoft.ServiceFabric
{
    [GeneratedCode("Microsoft.Windows.CsWin32", "0.3.18-beta+dc807e7787")]
    public static class PInvoke
    {
        public static HRESULT FabricCreateLocalClient(in Guid iid, out void* fabricClient);
        [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
        public static HRESULT FabricCreateLocalClient(Guid* iid, void** fabricClient);
    }
}

So, when using these functions, this error is encountered. The specified module could not be found.

The solution is to support custom values for "DefaultDllImportSearchPaths" in the generated code.

More details can be found here: https://github.com/youyuanwu/service-fabric-cs/issues/2

AArnott commented 10 months ago

Would specifying System32 | ApplicationDirectory | AssemblyDirectory be sufficient here? If not, what would be required?

youyuanwu commented 10 months ago

FabricCreateLocalClient function comes from FabricClient.dll. This dll lives inside directory C:\Program Files\Microsoft Service Fabric\bin\Fabric\Fabric.Code and is in the system env:PATH variable.

So to make this work the code needs to find FabricClient.dll in the right directory. I am not familiar with the dll searching in cs. But given the generated code, I think

[DefaultDllImportSearchPaths("C:\Program Files\Microsoft Service Fabric\bin\Fabric\Fabric.Code")] 

might work? Is it possible to look up dll in the system PATH like native application?

AArnott commented 10 months ago

You can't specify a path like that. The attribute only takes a flags enum. You can see the options here.

I'm not aware of any setting that will simply search all the directories in PATH for dependencies, even in native applications. I think native apps have the same set of options that is exposed to .NET applications through that enum. Note that, per the docs in the enum, an AddDllDirectory win32 function exists whereby you can explicitly add a directory to the dll search path. Then you'd need to set the UserDirectories flag on the enum so that .NET would honor that.

Frankly though, I think the simplest path for you may be to find the file yourself and load it using LoadLibrary. Once loaded, these p/invokes will work regardless of this enum.

youyuanwu commented 10 months ago

Using "LoadLibrary" suggested solved the issue.