Calling C++ exe functions from C# - c#

I'm trying to monitor a running application written in C++ using a different C# application.
In my C++ code I have defined an API:
_declspec(dllexport) //is this even possible when compiling an .exe?
int getSomething();
Is there a way to call this function from the C# code?
Will the classic approach work:
[DllImport("myexe.exe", CharSet = CharSet.Auto)]
public static extern int getSomething();

Yes, any PE executable can export functions this way. Just keep in mind that the compiler will sometimes mangle the export names, resulting in stuff like this:
MyAPIFunction#16
You can check that the names are OK by loading the executable file into a tool such as PEInfo.
You should be able to call it in exactly the same way you would a function in a DLL.
Update
Ok, so it looks like you want IPC, not a P/Invoke call. See this page for info on how to use named pipes in C#. And here's a great place to start looking for info on how to use named pipes in C++.

Yes, you can export functions from a .exe exactly like you can from a .dll and the way you've shown is the correct way to do that.
No, you can't interact with an existing process by doing that, just as loading a function from a .dll wouldn't allow you to interact with other processes using that .dll.

Related

How to dynamically load a native dll in c# .net standard?

I want to use something similar to NativeLibrary.TryLoad for a native dll in dot net standard. But I cannot find a method for it. Is there a good way to do this?
I know a can do things like
[DllImport(#"alib.dll")]
internal extern static int func();
but that is not what I want in this case. Im tracking a bug that cause a library to sometimes not load (from inside a dll that Im calling). So I want to preload it in my program and see if that helps.
You can use LoadLibrary or LoadLibraryEx (https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw).

Using a C++ library in C# winforms

I'm trying to use the SPARK particle system in OpenTK.
my project contains the header files in folders, with just two header files which only includes the others, and the folders contain the source files too.
I have tried several approaches so far, but nothing has worked for me yet, those are what I've tried:
1. P/Invoke
This is writing some code in your C++ project which built the dll and then using the DllImport attribute in C# (which obviously needs using System.Runtime.InteropServices;). I discovered the hard way that this doesn't work with classes, it only works for methods outside classes, so this approach was ineffective.
2. Wrapper classes
This is writing a class that contains a pointer to the original class. I discovered that the difficulty actually arises from calling unmanaged code(no automatic memory management) from managed code, that's why wrapper classes are needed, and that's why you have to redefine methods' signatures and let them call the original methods.
Of course this has advantages, like naming the classes and methods in a better way, but the library is so big so you can see the effort of this.
3. Use of an automatic wrapper:
This is a good approach, especially with xInterop++. I was really optimistic about this and thought it would work, it says "give me the .h files and the dll and I'll build the .NET dll for you". Good but doing so gives an error; in brief:
You must make sure .h files and the dll are consistent and that the
library works in a C++ project.
I have tried several things to deal with this error:
Knowing what the dll contains: it is difficult as I learned from Googling and from this site, so my try failed.
Putting header files in a new project and building it: received errors, fixed them, and then built the project and it worked well. I uploaded the dll file with the header files to xInterop. It then told the classes that were found but would then state that nothing was found! I searched and learned that the compiler must be told which classes are needed to be exposed by the dll by marking every class that is needed using the following statement:_declspec(dllexport).
I used Find & Replace to fix this thing and tried again and classes were shown, so I launched xInterop and received the same error.
It asked to ensure that the dll works. After verifying that the file worked I launched the program and linker errors were produced.
Here is where I'm stuck, these are the linker errors I get:
main.obj : error LNK2019: unresolved external symbol "void __cdecl
SPK::swapParticles(class SPK::Particle &,class SPK::Particle &)"
(?swapParticles#SPK##YAXAAVParticle#1#0#Z) referenced in function
"private: void __thiscall SPK::Pool::swapElements(class SPK::Particle &,class SPK::Particle
&)" (?swapElements#?$Pool#VParticle#SPK###SPK##AAEXAAVParticle#2#0#Z)
main.obj : error LNK2001: unresolved external symbol "unsigned int
SPK::randomSeed" (?randomSeed#SPK##3IA) main.obj : error LNK2001:
unresolved external symbol "unsigned long const SPK::NO_ID"
(?NO_ID#SPK##3KB) main.obj : error LNK2001: unresolved external symbol
"public: static float const * const SPK::Transformable::IDENTITY"
(?IDENTITY#Transformable#SPK##2QBMB)
This is the code that produced those errors:
#include "Extensions/Emitters/SPK_RandomEmitter.h"
using namespace SPK;
int main()
{
RandomEmitter e;
e.changeFlow(6);
e.getFlow();
return 0;
}
So that's my problem, I'm sorry for explaining too much but I've done a three days search without finding any solution.
PS:
the library is very big, so an automatic solution is a must.
This is a very, very unfriendly C++ library to have to interop with. Scratch the idea that pinvoke can work, C++ classes require C++/CLI wrappers. There are a great many classes with many small methods. The library depends on composition to generate effects so any approach that tries to do the interop with a few God classes is a dead avenue.
The most significant hazard is that it heavily relies on multiple inheritance. Not supported in .NET, this will defeat any tool that auto-generate wrappers. Also note that it only supports OpenGL rendering, not a terribly popular graphics api on Windows.
The library is attractive, and has been around for quite a while, but nobody has successfully ported it to .NET yet. This is unsurprising. In my opinion, you don't stand a chance. Only a rewrite could work.
PInvoke is the way to do what you are looking for. Doesn't matter if you have or do't have the code for that DLL so long you know the function signature.
Have a look at these articles from MSDN and code project that cover basics of PInvoke:
Platform Invoke Tutorial
P/Invoke Tutorial: Basics (Part 1)
Edit:
There are tools that can possibly generate DllImport signature for you. I have NOT tried any of these myself. Have a look:
P/Invoke Signature Generator
Easiest way to generate P/Invoke code?
This one
http://www.swig.org/
Hope that helps.
If your native dll exports some classes, then I would strongly suggest creating another native DLL wrapper for the original one. It should export a few functions and no classes at all.
Exported functioned could be something like:
my_lib_create_context( void ** const ppContext );
my_lib_delete_context( void * const pContext );
my_lib_do_something( void * const pContext, T param1, T param2 );
Inside my_lib_create_context() create an instance of your class and pass the pointer back through the ppContext parameter.
Inside my_lib_do_something() cast the pContext to a pointer of your class type and use it.
Also, when writing your wrapper, pay attention to calling convention, because you will need to pass that information to the .NET world (I think stdcall is default if not explicitly defined).
EDIT:
Regarding that part on how to do it:
Create a new C++ solution/project, select DLL type. Then add .def file to that project. Add to that file this:
EXPORTS
my_lib_create_context #1
my_lib_delete_context #2
my_lib_do_something #3
Then add some header file where you will put function signatures like this:
typedef void * SomeContext;
extern "C"
{
int __stdcall my_lib_create_context( /* [ out ] */ SomeContext * ppContext );
int __stdcall my_lib_delete_context( /* [ in ] */ SomeContext pContext );
// TO DO: ... you get it by now...
}
Implement these functions in .cpp file. Once you are done, create a wrapper in C# for this DLL and use it.
Hmm P/Invoke call GetProcessAdress .. so importing ABI problem is so so..
http://www.codeproject.com/Articles/18032/How-to-Marshal-a-C-Class
here are your answer give credit to those guy

How to reference .inl and .h files in C#

Update 1:
I am wondering whether I can reference to a .lib file, but it seems that I cannot.
If this is true, and I have no source code of the C++ project, How can I use its methods?
Btw, I'm using FastCV library.
I come across a situation that I need to call C++ methods from C# code.
The C++ generated files structure:
lib
--libfastcv.lib
--vc120.pdb inc
--fastcv.h
--fastcv.inl
--stdint.h
I know how to call C++ methods from C# :
[DllImport("libfastcv.lib",CallingConvention=CallingConvention.Cdecl)]
public static extern <ReturnType> <MethodName>(<Parameters>);
But I think the .h and .inl files need to be included in my C# project as well.
So how to include them?
Thank you very much.
They don't. Instead, you need to build/use binary-compatible types in your own code, and use them. (And, you importing a method from dll, not from lib).
You dont have to do any includes. The DLLImport should be enough.
To see the Methods you can import you can use DependencyWalker or my favourite Tool CFF Explorer
I often used any WINAPI functions where i need some constants defined in headers. I always had to define them in my C# code too, theres no way to "import" them.

How to call a C++ exported function from C#, in another process?

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.

Using vc++ Dll in C#

I am working on a c# crawler/Poster project, it crawls wordpress blogs, sites, using WebClient to download content.
Wordpress sites use a bug or i don't know, of WebClient, for some reason it does not accept all cookies, from wordpress blogs, it may be a measure to stop auto bots, spammers.
So decided to use Sockets, but seems sockets also has a few problems, it sometimes does not return full response, so not reliable, but i found a good working code in VC++, i am trying to use it in C#, but i dont know vc++ at all.
Here is the code
How do i create a dll of the above code?
I have created a simple dll project using vc++ but unable include the above code in the project.
Updated Link to Code
You can use platform invokes, creating a declaration for each function you need. Here's an example of importing the MessageBox WinAPI function (note that this is not the same as the MessageBox class in .NET!)
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);
Now that I have downloaded your code, I can say this...
Even if we got this code to compile, we still have to do the normal heavy lifting of interop between C++ and C#. And the code isn't even ready for that. The http_download.h file is a big set of inline classes. And the instructions for making C++ Code invokable from C# is to long to list here. You would basically have to get this code to compile as a DLL. Then from the DLL either export a set of "C" functions that invoke your C++ to do what you want. Or convert these C++ classes into COM objects with a type library.
But let's analyze what you are really trying to do:
You want to crawl web pages, but WebClient doesn't work.
So I think the real question you want to ask:
Why doesn't WordPress accept my cookies with WebClient?
And I really don't know the answer, because you haven't shared your WebClient code or elaborated what you think may be the issue. But I bet it's an easily solved problem.
I'm certain WebClient will be 10x easier to use than than some C++ code hacked up as one .h file that doesn't look very pretty. And it will be 100x time easier than trying to put together a HTTP library using pure sockets (which is what WebClient is, but it supports all the features you need, but haven't realized yet).
Sorry if I'm curt. I'm trying to encourage you to think about this a better way than doing it the hard way.
Create a class library by using the C++ code and add it as a reference to your C# project.

Categories