You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace MyApplication
{
static public class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("TestLibrary.dll",
CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetString();
}
public static class CommonUtils
{
/// <summary>
/// Loads given unmanaged library from the assembly.
/// This allows to embed .dll file as resource inside assembly.
/// Example:
/// string tempDllPath = LoadUnmanagedLibraryFromResource( Assembly.GetExecutingAssembly(),
/// "PInvokeTest.TestLibrary.dll",
/// "TestLibrary.dll");
/// </summary>
/// <param name="assembly"></param>
/// <param name="libraryResourceName"></param>
/// <param name="libraryName"></param>
/// <returns></returns>
public static string LoadUnmanagedLibraryFromResource(Assembly assembly,
string libraryResourceName,
string libraryName)
{
string tempDllPath = string.Empty;
using (Stream s = assembly.GetManifestResourceStream(libraryResourceName))
{
byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);
string assemblyPath = Path.GetDirectoryName(assembly.Location);
tempDllPath = Path.Combine(assemblyPath, libraryName);
File.WriteAllBytes(tempDllPath, data);
}
NativeMethods.LoadLibrary(libraryName);
return tempDllPath;
}
}
class Program
{
static void Main(string[] args)
{
string resourceName = "MyApplication.TestLibrary.dll";
string libraryName = "TestLibrary.dll";
// create and load library from the resource
string tempDllPath = CommonUtils.LoadUnmanagedLibraryFromResource(Assembly.GetExecutingAssembly(),
resourceName,
libraryName);
// invoke native library function
string output = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(NativeMethods.GetString());
Console.WriteLine(output);
}
}
}
The text was updated successfully, but these errors were encountered:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace MyApplication
{
static public class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
}
The text was updated successfully, but these errors were encountered: