====== 5.1 P/Invoke - Integracija DLL-ova ====== Ova stranica pokazuje kako koristiti OpenSSL putem P/Invoke u .NET-u. ---- ===== Što je P/Invoke? ===== **P/Invoke** (Platform Invoke) omogućuje pozivanje nativnih DLL funkcija iz .NET-a: .NET Kod → P/Invoke → libcrypto-3-x64.dll → OpenSSL ---- ===== Pripremite DLL-ove ===== ==== 1. Kopirajte DLL-ove u Projekt ==== cd MojProjekt copy "D:\Projects\openssl-3.6.0\bin\bin\libcrypto-3-x64.dll" .\ copy "D:\Projects\openssl-3.6.0\bin\bin\libssl-3-x64.dll" .\ ==== 2. Izmijenite .csproj ==== net8.0 PreserveNewest PreserveNewest ---- ===== Jednostavan P/Invoke Primjer ===== using System; using System.Runtime.InteropServices; namespace MojProjekt; public static class OpenSslInterop { private const string LIBCRYPTO = "libcrypto-3-x64.dll"; // Inicijalizacija [DllImport(LIBCRYPTO, CallingConvention = CallingConvention.Cdecl)] public static extern int OPENSSL_init_crypto(ulong opts, IntPtr settings); // Dohvati verziju [DllImport(LIBCRYPTO, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr OpenSSL_version(int type); // Konstante public const int OPENSSL_VERSION_STRING = 6; public const ulong OPENSSL_INIT_LOAD_CRYPTO_STRINGS = 0x00000002; public const ulong OPENSSL_INIT_ADD_ALL_CIPHERS = 0x00000004; public const ulong OPENSSL_INIT_ADD_ALL_DIGESTS = 0x00000008; public static void Initialize() { OPENSSL_init_crypto( OPENSSL_INIT_LOAD_CRYPTO_STRINGS | OPENSSL_INIT_ADD_ALL_CIPHERS | OPENSSL_INIT_ADD_ALL_DIGESTS, IntPtr.Zero); } public static string GetVersion() { var ptr = OpenSSL_version(OPENSSL_VERSION_STRING); return Marshal.PtrToStringAnsi(ptr) ?? "Unknown"; } } // Uporaba: class Program { static void Main() { OpenSslInterop.Initialize(); Console.WriteLine($"OpenSSL Verzija: {OpenSslInterop.GetVersion()}"); } } ---- ===== Česte Greške ===== ==== "DLL not found" ==== System.DllNotFoundException: Unable to load DLL 'libcrypto-3-x64.dll' **Rješenje:** - DLL-ovi prisutni u izlaznom direktoriju (bin/Debug/)? - .csproj ''CopyToOutputDirectory'' ispravan? - Platforma ispravna? (x64 vs x86) ==== "Entry point not found" ==== System.EntryPointNotFoundException: Unable to find entry point 'XYZ' **Rješenje:** - Ime funkcije ispravno napisano? - ''CallingConvention.Cdecl'' postavljen? - Verzija OpenSSL-a podržava funkciju? ---- ===== Nastavite na ===== * [[.:nuget-grundlagen|Stvaranje NuGet paketa]] * [[.:verteilung:start|6. Distribucija]] ---- //Wolfgang van der Stille @ EMSR DATA d.o.o. - Post-Quantum Cryptography Professional//