About DllImport in C#

Asked 2 years ago, Updated 2 years ago, 51 views

Hello, thank you for your help.

I would like to import the DLL of the current directory explicitly in DllImport of C#, but it seems that compilation error occurs with the following source.

using System;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
public class main {
string curdir=System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
[DllImport(cardir+"\\test.dll", CharSet=CharSet.Ansi)]
external static int test (int num);
(omitted later)

The compilation errors are as follows:
test.cs(7,16): error CS0120: Non-static field, method, or property 'main.cardir' requires object reference

Is there any way to explicitly load DLLs in the current directory?

Thank you for your cooperation.

c#

2022-09-30 10:52

1 Answers

It appears in the following article.
How do I specify dll at runtime in DllImport?

Conclusion
By reading DLLs in the LoadLibrary function before loading dll in DllImport, dll of the same name will now refer to the loaded DLLs.

If we take the above action, wouldn't it be better to just use the file name instead of the path specification below?

 [DllImport(cardir+"\\test.dll", CharSet=CharSet.Ansi)]

I searched again and found this article.
This one will make the source code cleaner.
Read the DLL.Change the order of search paths for DLLs...

Application configuration file (.exe.config) or DLL/COM redirection file (.exe.local).

This is the Microsoft article related to this.
Element<Probe>Element
DLL/COM redirection


2022-09-30 10:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.