This repository has been archived by the owner on Nov 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 508
/
LoadLibrary.c
90 lines (70 loc) · 2.29 KB
/
LoadLibrary.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//On unix make sure to compile using -ldl flag.
//Set this value accordingly to your workspace settings
#define PathToLibrary "./bin/Debug/netstandard2.0/linux-x64/native/NativeLibrary.so"
#ifdef _WIN32
#include "windows.h"
#define symLoad GetProcAddress
#else
#include "dlfcn.h"
#include <unistd.h>
#define symLoad dlsym
#endif
#include <stdlib.h>
#include <stdio.h>
#ifndef F_OK
#define F_OK 0
#endif
int callSumFunc(char *path, char *funcName, int a, int b);
char *callSumStringFunc(char *path, char *funcName, char *a, char *b);
int main()
{
// Check if the library file exists
if (access(PathToLibrary, F_OK) == -1)
{
puts("Couldn't find library at the specified path");
return 0;
}
// Sum two integers
int sum = callSumFunc(PathToLibrary, "add", 2, 8);
printf("The sum is %d \n", sum);
// Concatenate two strings
char *sumstring = callSumStringFunc(PathToLibrary, "sumstring", "ok", "ko");
printf("The concatenated string is %s \n", sumstring);
// Free string
free(sumstring);
}
int callSumFunc(char *path, char *funcName, int firstInt, int secondInt)
{
// Call sum function defined in C# shared library
#ifdef _WIN32
HINSTANCE handle = LoadLibraryA(path);
#else
void *handle = dlopen(path, RTLD_LAZY);
#endif
typedef int(*myFunc)();
myFunc MyImport = symLoad(handle, funcName);
int result = MyImport(firstInt, secondInt);
// CoreRT libraries do not support unloading
// See https://github.com/dotnet/corert/issues/7887
return result;
}
char *callSumStringFunc(char *path, char *funcName, char *firstString, char *secondString)
{
// Library loading
#ifdef _WIN32
HINSTANCE handle = LoadLibraryA(path);
#else
void *handle = dlopen(path, RTLD_LAZY);
#endif
// Declare a typedef
typedef char *(*myFunc)();
// Import Symbol named funcName
myFunc MyImport = symLoad(handle, funcName);
// The C# function will return a pointer
char *result = MyImport(firstString, secondString);
// CoreRT libraries do not support unloading
// See https://github.com/dotnet/corert/issues/7887
return result;
}