D
D
DailyDDose2017-12-13 19:04:24
JavaScript
DailyDDose, 2017-12-13 19:04:24

How to code a C-like DLL in C# (which can be dynamically loaded)?

For example, in C, the export of functions looks like this:

extern "C" __declspec(dllexport) int Run() {
  return 488;
}

In the main program, I load the DLLs I need and use the functions they export like this:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace wfa
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyClass.LoadDll(@"D:\dev\csharp\test\Debug\cpx.dll");
            var result = MyClass.Run().ToString();
            MessageBox.Show(result, result);
        }
    }

    public class FunctionLoader
    {
        [DllImport("Kernel32.dll")]
        private static extern IntPtr LoadLibrary(string path);

        [DllImport("Kernel32.dll")]
        private static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

        public static Delegate LoadFunction<T>(string dllPath, string functionName)
        {
            var hModule = LoadLibrary(dllPath);
            var functionAddress = GetProcAddress(hModule, functionName);
            return Marshal.GetDelegateForFunctionPointer(functionAddress, typeof(T));
        }
    }

    public class MyClass
    {
        public delegate int FnDelegate();
        public static FnDelegate Run;

        public static void LoadDll(string path)
        {
            Run = (FnDelegate)FunctionLoader.LoadFunction<FnDelegate>(path, "Run");
        }
    }
}

Bwl1EUeO-mU.jpg
full source code: https://github.com/DailyDDose/DllTesting

Answer the question

In order to leave comments, you need to log in

4 answer(s)
2
2CHEVSKII, 2019-10-02
@2chevskii

I don't know what form the response comes in, but anyway - you need to parse the data from the string into the object, and then access its field, below is an example

function getCityName(json){
    var obj = JSON.parse(json)

    var cityName = obj['city_name'] // предположим, что в json нужное нам поле называется "city_name"

    return cityName;
}

A
Alexander, 2017-12-13
@alexr64

This is a development of what you have tried.
There is a Nuget package.

J
John_Nash, 2017-12-14
@John_Nash

C# is not designed for such tasks
If you need to make calls from native code to NET assemblies, use COM or C++ CLI wrappers

D
DailyDDose, 2017-12-13
@DailyDDose

Robert Giesecke's Unmanaged Exports solution doesn't build, compile-time errors occur

class Test
{
    [DllExport("add", CallingConvention = CallingConvention.Cdecl)]
    public static int Run()
    {
        return 1082;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question