简体   繁体   中英

Unable to execute extern c function in Unity 5

Currently i am trying to embed CEF into Unity. I have managed to compile cefsimple example as dll and use it in ordinary console application by using DllImport with following code:

[DllImport("cefsimple")]
public static extern ulong StartCustom();
static void Main(string[] args)
{
    StartCustom();
}

and corresponding C function:

extern "C" __declspec (dllexport) int StartCustom() {
    return wWinMain(nullptr, nullptr, nullptr, 0);
}

(All the necessary files I have moved to a folder with created .exe file)

But if i try to do the same in Unity i am getting

Failed to load 'Assets/Plugins/cefsimple.dll' with error 'The specified procedure could not be found.

DllNotFoundException: cefsimple
Launcher.Init () (at Assets/Plugins/Launcher.cs:13)

Is there are any way to fix this?

first you most define dll import and export directives in your c application like this:

#ifndef YOUR_SOURCE_NAME_H //header guard
#define YOUR_SOURCE_NAME_H

    #define YOUR_SOURCE_NAME_EXPORT (1)

    #ifdef YOUR_SOURCE_NAME_EXPORT
        #define DLL_USAGE_MODE extern "C"  __declspec(dllexport)   // export DLL information
    #else
        #define DLL_USAGE_MODE  extern "C" __declspec(dllimport)   // import DLL information
    #endif


#endif // YOUR_SOURCE_NAME_H

you most put DLL_USAGE_MODE before your function name to make it accessable from outside. for example you have below function in your c DLL :

DLL_USAGE_MODE int saySomthing(const char* pText) {
    printf("\n%s", pText);
    return 0;
}

now in your c# application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

class Program {
    [DllImport("address_of_your_dll.dll", EntryPoint = "saySomthing", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int saySomthing(string text);

    static void Main(string[] args) {
        saySomthing("HelloWorld !!");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM