I am trying to make a program which will need to execute a lengthy algorithm over and over again, so C++seemed like the obvious choice to me. However, in order to make it look aesthetically pleasing, and to make its other functions easier to make, I built it in C# and made the algorithm in C++.
As far as I am aware, the best way for me to use the C++ function in my C# program is to PInvoke it. However, when I try to PInvoke the function from the DLL, I get an error saying
"Unable to find an entry point named <name> in DLL"
When I made my DLL, I used Visual C++ and created a Win32 Console application, selected DLL from the choices, and created the function in the test.cpp file. What did I do wrong?
You need to export the function in the native DLL.
Related
I can't reference ImageSearch.dll in my project. I've been trying for days and can't get any further. it seems to me that i'm the only one with this problem and i don't know what to do next. Is it possible to reference a .dll manually, for example via lines of code? It's nerve wracking and need this or a similar feature.
I keep getting the following error:
Could not add a reference to imagesearch.dll. Make sure the file is accessible and is a valid assembly or COM component.
enter image description here
Hope someone can help me...
That message is telling you that the dll you're trying to reference is something that .NET doesn't know how to work with automatically. This means it has no idea what functions are in the dll or how they work. So, if a dll isn't a .NET assembly or exposed via COM, then you can use PInvoke (Platform Invoke).
Don't add the dll as a reference to your project at all, instead add it as a content file that gets output with the rest of your compiled code. Getting PInvoke to work with an arbitrary DLL can be quite complicated, so be prepared for some headaches. There's an entire website with examples of how to pinvoke for all sorts of libraries at http://pinvoke.net/ that will give you lots of ideas.
Then you can call methods in the dll by doing something like:
// Import ImageSearch.dll (containing the function we need) and define
// the method corresponding to the native function.
[DllImport("ImageSearch.dll"]
private static extern int FindImage(string imagePath);
Obviously I have no idea what imagesearch.dll is or does, so I have no idea what the actual PInvoke function should look like, you'll have to figure that out from the dll's interface.
https://learn.microsoft.com/en-us/dotnet/standard/native-interop/pinvoke
I'm writing an add-in that runs in-process. I'm reliably able to discover the memory address of a DLL that is already loaded in that process. The memory at the offset clearly shows an "MZ" DOS header and a "PE" header. Later, there appears to be the names of exported functions etc. This walks and talks like a loaded DLL.
So, now, I'd like to discover more about what the DLL is, and more interestingly, what I might be able to do with it.
I've used PE utilities in the past, but they've always worked with file-based DLLs. How can I list the exported functions of an in-memory DLL, other than by inspecting the process in a hex editor? Is there any way to discover the file-based DLL that is currently loaded? (I'm not overly familiar with the linking that I think takes place when the dll is loaded.)
If I have the names of the exported functions, is it just a matter of trying to call those functions, and guessing their arguments and return values? Or is there some more robust reverse engineering that could be performed?
Given the starting address of the DLL, and a function name, how would I go about making a call in C#?
There are actually many questions here (and some are pretty vast). I'll try providing answers to some.
To get the handle of a module (.dll) loaded in the current process use
[MSDN]: GetModuleHandleEx function, whether its name or address is known (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS flag)
To get the file name containing the code of a loaded .dll use [MSDN]: GetModuleFileName function. At this point you'll be able to use PE utilities that you mentioned (Dependency Walker or [MSDN]: Sysinternals Suite can be very useful)
Apparently, getting the functions signatures from a .dll is not a trivial task (sometimes it's quite impossible). Here are 3 URLs, but Google would yield tons of results on this topic:
[MSDN]: how can I get metadata (signature with parameters and return type) of C++ dll
[SO]: Is there any native DLL export functions viewer?
[SO]: Get signatures of exported functions in a DLL
But a .dll comes with one or more header file(s) that contain(s) (among other things) the functions/classes declarations. Lacking the header(s) would mean that either:
The .dll symbols are for internal purposes only (and not to be called "manually")
They are private (e.g. protected by a license), and in that case reverse engineering them wouldn't be very ethical
Anyway, considering that one way or another you get the functions names and signatures, you can load the functions via [MSDN]: GetProcAddress function, and then call them.
Doing everything from .NET (C#) (again, function names and signatures are required), only adds an extra level of complexity because C# code runs in managed environment, while C/C++ runs in native environment, and when data is exchanged between the 2 environments it needs to be marshalled/unmarshalled ([MSDN]: Overview of Marshaling in C++).
Below are 3 URLs, but again, Internet is full of information:
[MSDN]: Calling Native Functions from Managed Code
[SO]: Is it possible to call a C function from C#.Net
[SO]: Calling C DLL from C#
I have a nice .net assembly of core matlab functions, created of course with the matlab compiler. For functions that accept numbers or arrays of numbers, this is fine; I can write code in c# without having to revert to matlab (well, the RCM has to be installed; that’s fine).
For functions that must reference other functions, however, the only way I can find so far to get a c# programme going is to compile both functions into the assembly. To explain better, let’s say I have a library in which I’ve stored the ode45 routine. If I want to solve a specific equation, let’s say something simple like dy/dx = -y, then I have to create a matlab script file which may be written as follows:
function dydx = diffeq(x, y)
dydx = -y
[obviously the analytical solution exists, but for the sake of this example let’s say I want to solve it this way]
Now in order to solve this equation, I would have to add this function as a method in my class to be compiled into the .net assembly. This of course ruins the generality of my library; I want application-specific equations in a different library to my core math function library. That is, the ODE45 method should reside in a “more core” library than the library in which the “diffeq” method would reside.
More than that, I would much prefer to create the “diffeq” method in a c# class that I can edit directly in e.g. VS2012. I would like to edit the equation directly rather than having to enter matlab each time and recompile an assembly.
To solve this problem, I have gone to the extent of decompiling the assembly which contains both the ode45 code and my differential equation method; it turns out the assembly is nothing but an interface to the MCR; the diffeq methods in the assembly return something like the following:
return mcr.EvaluateFunction(numArgsOut, “diffeq”, new object[0]);
We note that the function/method “diffeq” is not part of the MCR; MCR does not change. However, I can’t find the equation anywhere in the assembly.
Which begs the question “Dude, where’s my function?”
There is a ‘resources’ component of the assembly in which we find [classname].ctf, and in that we’ll find some machine code. This looks encrypted, but the equation might be hidden in there. If so, that would be a deliberate attempt to prevent when I am attempting, and kudos to MathWorks for making it impossible for me to avoid having to enter the matlab application!
However, there doesn’t seem to be anything in licensing to prevent what I want to do; I think it would be great if mathworks would allow as open an approach as that, but in the interrim, does anyone know how to do this?
The "MATLAB Compiler" has a somewhat misleading name. It is more of a deployment solution than a compiler in the actual sense (see note below). It is mainly intended to distribute MATLAB applications to end-users without requiring a full MATLAB installation on their part (only the royalty-free MCR runtime needs to be installed).
The MCR is in fact a stripped-down version of the MATLAB engine along with accompanying libraries.
When you use MATLAB Compiler to generate a binary package, the result is a target-specific wrapper (be it a standalone application, C/C++ shared library, Java package, or a .NET assembly) that calls the MCR runtime. The binary generated includes an embedded CTF archive containing all the original MATLAB content (your M-files and other dependencies) but in an encrypted form. When first executed, the CTF archive is extracted to a temp folder, and the M-files (still encrypted) are then interpreted by the MCR at runtime like typical MATLAB code.
There is an option in deploytool (mcc -C) to tell the compiler not to embed the CTF archive inside the binary as a resource, instead to place it as a seperate file next to the generated binary (this CTF archive can be inspected as a regular ZIP-file, but the source files inside are still encrypted of course).
See the following documentation page for more information:
Application Deployment Products and the Compiler Apps
PS: The truth is MATLAB Compiler started out as a product to convert MATLAB code into full C/C++ code which used the now discontinued "MATLAB C/C++ Math Library" (no runtime requirement, you just compile the generated C++ code and link to certain shared libraries; the result is a true compiled executable not a wrapper). This functionality completely changed around the time MATLAB 7 was released (the reason being that the old way only supported a subset of the MATLAB language, while using the current MCR mechanism enables deploying almost any code). Years later, MATLAB added a new product to replace the once-removed functionality of code translation, namely the MATLAB Coder.
I haven't found anything useful related to this problem after some serious google lurking, so I'll ask it here.
I have a program that's made in C# that injects a DLL into another process, fairly trivial. It Calls CreateRemoteThread and LoadLibrary from kernel32.dll with [DllImport].
My DLL once loaded then waits for authentication from the C# program, due to security reasons, I can't have this data transferred using sockets. So I have my DLL export a function that's planned to be called from the C# program with authentication data.
The exported function takes two arguments, it is as follows :
extern "C" __declspec(dllexport) void DoStuff( const char* ccString1, const char* ccString2 ){
// Do stuff
}
Since as the DLL isn't in the same address space as the C# program, I can't use [DllImport] to get and the call the exported function.
My second idea was to use CreateRemoteThread to call the function, though that can only be passed 1 argument whereas I need two, it'd also be difficult because I'd need to call the return of GetProcAddress, I can't simply call by exported function directly.
So, how would I go about achieving this?
Thanks
[DllImport] is the same as GetProcAddress. C# does not load the DLL until the first call, so the .NET can do the security checks before calling the DLL.
If you don't trust the DLL at all, then it's better to split de C# program in two. One program connected via Remoting/WCF/IPC to the second one, and the second one connects to the C DLL via DllImport. This solution is typically used when you don't trust C DLL stability or memory allocation because the second program (the one that call de C DLL) can be restarted without restarting the main program. Example of this pattern: some windows drivers (with the exception that they don't use C# at this time).
You could use Non-persisted memory-mapped files to exchange data between the application and the DLL.
I've searched good and Stack Overflow but couldn't find an answer to what I was looking for. Is there anyway to hook the call of Python functions from within C++/C#? Capture the function call plus it parameters?
Edit with an example:
def a(pOne):
//do stuff
def b():
a("a")
So on the call to 'a' I want C++ to hook that function (assuming the function name is known) and execute a C++ function/event on the call to 'a' with the parameters passed to the C++ function/event being the value of what was passed in for 'pOne'.
Thanks
There a couple of different options for C++ depending on what you want to do.
The best way to do what you want to do is to 'extend' Python.
My Favorite way to do this is Boost.Python
You can also use the raw C-API though I wouldn't recommend this.
For some examples of embedding and extending with Boost.Python you can look at this project I have been working on.
If you just want to write some C++ code and make it callable from Python, you do that by Extending and Embedding the Python Interpreter. (Actually, just Extending; ignore the other half.)
Basically, if you write a new module foo, anyone can import foo and call foo.a("a"), and it doesn't matter if module foo is implemented as a Python file foo.py, or compiled from foo.cpp into a dynamic library foo.so.
For that, as Kyle C suggests, there are a number of higher-level ways to do this so you don't need to deal with the C API directly. (In addition to his suggestion of Boost.Python, I'd also suggest looking at Cython, which lets you write the code in an almost-Python language that can talk directly to your C++, while also exposing things directly to Python.)
However, that isn't what you asked for. What you want to be able to do is take some function that's defined in Python code, and hook it to do something different. For that, you really do need to read the Extending and Embedding documentation linked above. You're going to have to write an embedded interpreter, reproduce some of the behavior (exactly how much depends on where exactly you want to hook it), and make sure that wherever PyObject_Call or a similar function would have been called, it first checks whether that object is the a function and, if so, calls your hook code.
This is going to be pretty difficult. If you haven't written an embedded Python interpreter yet, go do that before you even think about how to hook it.
It's worth noting that it's probably much, much easier to do the hooking from within Python than from outside the interpreter. (If you've never heard of "monkeypatching", go google that.) And you can always make your Python hook call code from a module that you built in C++, or even call directly into a compiled .so file via ctypes.
Finally, if you want to hook some running interpreter instance at runtime, that's even more difficult. You obviously need to be able to do some kind of debug/trace/etc. attach and code insertion, and the details of that are entirely dependent on your platform. Then, you'll want to do the same thing you would have done in the previous hard version, except that you'll have to do it by intercepting calls to, e.g., PyObject_Call (from libpython.so/Python.dll/Python.framework/whatever) to go through your hooks first. If you don't already know how to hook SO calls on your platform, you need to learn that before you can even think about hooking Python code from outside.
Do you have reasons not to alter the in-python code? If not, why not write an extension module or a python ctypes call to your dll, and wrap a with a decorator that calls your hook?
import my_cpp_module
def hook_a_to_call_my_cpp_module(orig_a):
def replacement_a(pOne):
try:
my_cpp_module.my_cpp_function(pOne)
finally:
return orig_a(pOne)
#
return replacement_a
#hook_a_to_call_my_cpp_module
def a(pOne):
pass
you can even do this without touching the source file which has a, like this:
# in this other file you import the module that contains function a
import the_py_that_has_a
# next line just to avoid copy-pasting the above code from my answer here again
from the_decorator_from_the_previous_example import hook_a_to_call_my_cpp_module
the_py_that_has_a.a = hook_a_to_call_my_cpp_module(the_py_that_has_a.a)
If you have some reasons not to alter your py code at all, could you state them in a comment?