I am creating a Windows 10 application that works with files. For the GUI I am using UWP (C#) and for the file processing I want to use the C language (Visual Studio 2019).
I have tried these solutions (none of them worked):
C program created with Windows Desktop Wizard (DLL), then DllImport
Tried to add it to the UWP by using DllImport (which in a C# Console App program worked).
The code in the C file:
#include<stdio.h>
_declspec(dllexport) int getNumberOfFiles()
{
...
}
The code in the C# UWP app:
[DllImport(#"...\WorkFilesDll\Debug\WorkFilesDll.dll", EntryPoint = "getNumberOfFiles", CallingConvention = CallingConvention.Cdecl)]
internal static extern int getNumberOfFiles();
The following exception is thrown:
System.DllNotFoundException HResult=0x80131524 Message=Unable
to load DLL '...\WorkFilesDll\Debug\WorkFilesDll.dll' or one of its
dependencies: Access is denied. (Exception from HRESULT: 0x80070005
(E_ACCESSDENIED))
C program created with Windows Desktop Wizard (DLL), then add as reference
Tried to add the same dll as reference (References->Add Reference->Browse->Add->OK).
After pressing the OK button, the following message indicates the failure:
A reference to "...\WorkFilesDll\Debug\WorkFilesDll.dll" could not be
added. Please make sure that the file is accessible, and that is a
valid assembly or COM component.
I created other types of projects for the C code (C++, UWP): Dll (Universal Windows), Windows Runtime Component (Universal Windows). The results were the same.
I created other types of projects (C#, UWP): Class Library (Universal Windows), Windows Runtime Component (Universal Windows), in order to add theses projects to the UWP and to add to these projects the dll mentioned above (the C code to be added indirectly to the UWP). The results were the same.
I have found many questions and articles like this, but I didn't see a clear answer or the answers didn't work for me. Some of them are:
https://learn.microsoft.com/en-us/cpp/cppcx/dlls-c-cx?view=msvc-160
https://www.c-sharpcorner.com/forums/how-to-use-cpp-dlls-in-c-sharp-uwp-projects
How to call a function from DLL in UWP?
Can you use C++ DLLs in C# code in a UWP?
https://learn.microsoft.com/en-us/cpp/porting/how-to-use-existing-cpp-code-in-a-universal-windows-platform-app?view=msvc-160
I have also read about static libraries. I have failed in implementing them.
How can I put the C code in UWP (C#)?
Are static libraries the answer to my application?
Which are better for this application: the DLLs or the static libraries? Why?
Thank you!
Please check the following steps:
Create a C# UWP project in a new solution.
Add a C++ DLL(Universal Windows) project(named MyDll1) in the same solution.
Add your C code in the C++ DLL project. For example:
//MyDll1.h
#pragma once
extern "C" _declspec(dllexport) int Sum(int a, int b);
//MyDll1.cpp
#include "pch.h"
#include "MyDll1.h"
int Sum(int a, int b)
{
return a + b;
}
Add a Windows Runtime Component(C++/WinRT) project in the same project.
Right-click on the name of the Windows Runtime Component(C++/WinRT) project, and select option Add > Reference, check your DLL project in Projects tab. Click OK.
There is an auto-generated class Class, you could use the class or add other class(Add > New Item > Code > Midl File(.idl)) as needed. The new class must be generated from a midl file. You could get more information about authoring api referring to the document.
Take Class class as an example. Include the header file of dll in Windows Runtime Component(C++/WinRT) project.
//Class.h
#include "..\MyDll1\MyDll1.h"
There is a sample method named MyProperty shown in Class class. The MyProperty method is added to the Class.idl file and the complier will generate the corresponding methods in Class.h and Class.cpp after you build the project. And you need to go to the locations \RuntimeComponent\ RuntimeComponent \Generated Files\sources\Class.h and Class.cpp in File Explorer and open the .h and .cpp file to copy the generated methods into your code in Visual Studio. You could use MyProperty method to pass values to C# project or add other methods in classes. Refer to the document for more information about how to add new method in idl file.
You could call the Sum(int a, int b) of MyDll1 project in MyProperty method.
int32_t Class::MyProperty()
{
int t = Sum(1, 2);
return t;
}
Right-click on the name of the C# UWP project, and select option Add > Reference, check your Windows Runtime Component(C++/WinRT) project in Projects. Click OK.
Add include statement in C# UWP project.
using RuntimeComponent; // RuntimeComponent is the name of Windows Runtime Component(C++/WinRT) project.
You could call the MyProperty method in C# UWP project.
RuntimeComponent.Class myClass = new Class();
var value = myClass.MyProperty;
Related
I have code written in ANSI C that I would like to use in C#. I have compiled the C code into a DLL and created C# wrapper classes to interop with the C code. The point of the wrapper is to simplify a users interaction with the underlying C code.
[DllImport(DLL, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
private static extern void PrintHelloWorld();
public void PrintHelloWorldC()
{
PrintHelloWorld();
}
Above is a simplified example of what I have done so far. Now, I am trying to create a DLL from the C# wrapper classes I wrote. From here I could give both the DLLs created and someone would be able to interact with the C# based DLL to interact with the underlying C based DLL. Below is what I have done and what problem I am having.
I compile the C code into a DLL in Visual Studio 2019 with my Configuration=Release and Platform=Win32.
I compile my C# classes into a DLL in Visual Studio 2019 with my
Configuration=Release, Platform=Win32, and Platform Target as x86.
I create a new project and link my C# DLL and set Platform Target as x86.
I put my C DLL into the Debug folder of the project so that it is available to the C# DLL through the marshal directive.
I try to make a call into the C# DLL and below are the chain of events occurring.
Program calls C# DLL method PrintHelloWorldC() and is successful
Within PrintHelloWorldC() it tries to make a call to PrintHelloWorld();.
Following Error Occurs:
System.BadImageFormatException
HResult=0x8007000B
Message=An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
My research yielded that it was most likely a mismatch in Platform Target between the DLLs and Test Project, however, I have double checked all the configurations and they should all be compiled for x86.
Below is what additional testing I have done.
Created a C# Project, and wrote simple code to make a call directly into the C based DLL. This works fine.
It seems that as soon as I try to use the two DLLs on top of each other in another project I start facing issues.
Any help or guidance is appreciated. Thanks in advance!
I Have a ANVIZ T5 Pro Proximity reader, but I don't have a Proper SDK.
So I found the DLL files in installed location "CrossChex" application.
Now I have DLL files called,
ACE.DLL
AvzScanner.DLL
FaceSdk_V1.0.ocx
FaceSdk_V2.0.ocx
Facial.DLL
When I add a .dll file as a reference in C# application it shows an error :
A reference to the "....dll" could not be added.Please make sure that the file is accessible and that it is a valid assembly or COM component.
when I add the DLL it's getting below error massage.
It is because compiled version of DLL.
You have to import native wrote dll like this:
[DllImport("tc400.dll")]
public static extern int methodName();
It will be method of class where you declare it.
But you have to know method names to include it and use.
Good luck
This question already has answers here:
Is it possible to embed C code in a C# project?
(4 answers)
Closed 5 years ago.
I am confused on how to reference my c code from my c# code. I have read around and realized that DLL's are useful, but I do not understand how to connect my dll. From my understanding I make the dll from my c code? Please help
C# (visual studio code)
public partial class Form1: Form{
[DllImport("simple.dll", CallingConvention = CallingConvention.Cdec1)]
public static extern void pinfo(string str);
private void button1_Click(object sender, EventArgs e){
pinfo("yay");
}
}
C code - simple.c
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
__declspec( dllexport ) void pinfo(char* str){
printf("You are in the method %s\n, str);
}
int main(void){
}
my question is how do I connect the c code to the c# code so that the line "You are in the method yay" prints out? I do not understand how to link a dll file to visual studio or how to create the dll file. thanks
There are 3 main steps for getting P/Invoke (DllImport) working in .NET:
Export the function from the C/C++ project.
In Visual C++, use the __declspec( dllexport ) and extern "C" modifiers to, respectively, tell the compiler to export the function in the DLL so it is visible by name, and to not mangle the name either - otherwise the compiler will remove the function entirely if it has no callers inside the project ("dead-code removal"). Functions can also be exported by an ordinal number instead, which presumably is not what you're interested in.
Ensure you're building for the same ISA.
When you use P/Invoke in .NET, the DLL you reference will be loaded into the hosting .NET process, so the DLL must be built to the same CPU instruction-set as the current .NET process. .NET projects run in AnyCPU mode by default, but in recent versions of Visual Studio they "prefer" 32-bit (x86) mode instead of 64-bit (x64 / AMD64). To prevent any confusion, decide if you want 32-bit or 64-bit mode and force your .NET project to build only for that ISA and then set your C/C++ project to build for that ISA too.
Ensure the target DLL file is located in the PATH of the .NET executable - typically this means simply placing it in the same bin output directory as the built .NET executable.
Note that as this DLL file is not a .NET assembly there is no concept of a "project reference" or "assembly reference", so you need to configure your project specifically so that Visual Studio (MSBuild) will copy the DLL file to your bin folder - you can do this by adding the DLL file to your .NET project root in Solution Explorer, then selecting the file and open the Properties window and choose "Build action: Content." and "Copy to output directory: Always".
Regarding "linking" - DLLs are not linked at compile-time - the clue is in the name: "dynamic-linking": the linking is performed at runtime by the operating system, not by the compiler.
For more information on P/Invoke, I recommend reading this QA: Why are Cdecl calls often mismatched in the "standard" P/Invoke Convention?
I wrote a C++ Class Library in Visual Studio that just defines a function that invokes some Python:
#pragma once
#include <Python.h>
extern "C"
__declspec(dllexport)
void python()
{
Py_Initialize();
PyRun_SimpleString("2 + 2");
}
I made another project in the same solution that was a C# Blank Universal app. I tried to reference the DLL generated from the previous project I mentioned:
using System;
...
namespace StartupApp
{
...
sealed partial class App : Application
{
private const string CPPPythonInterfaceDLL = #"pathtodll";
[DllImport(CPPPythonInterfaceDLL, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
private static extern void python();
public static void Python()
{
python();
}
...
public App()
{
...
Python();
}
...
}
}
The app is in a Release configuration.
Whenever I try to run the app on my Local Machine, it always gives an error:
The program '[2272] StartupApp.exe' has exited with code -1073741790 (0xc0000022).
Activation of the Windows Store app 'ab6a8ef2-1fa8-4cc7-b7b3-fb7420af7dc3_7dk3a6v9mg4g6!App' failed with error 'The app didn't start'.
So my question is this: can I reference a C++ class library from a C# UWP project? Or does the security on UWP apps not allow this?
Or is it because of Python.h?
EDIT:
I built the project with a DLL project and a Runtime Component that wrapped it, and now I have this error:
An exception of type 'System
'System.DllNotFoundException' occurred in StartupApp.exe but was not handled in user code
Additional information: Unable to load DLL 'pathtodll': Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
I added a user to the DLL with the object name "Everyone" (I am not sure how else to give everyone permissions) but the error still comes up.
Firstly, UWP can't consume a legacy C++ dll just by DLLImport.
If you want to expose legacy c++ functions to C#, the first suggestion is to wrap that C++ logic using a WinRT component. Then you can reference this component in UWP application by following steps: adding it to the project, open the files' properties in the Solution Explorer window, and mark them as content to be included in the app package. This post would be helpful. This one provides more detailed steps.
If you want to PInvoke the dll, you can follow these steps (You can refer to this MSDN post):
Add win32 dll into your UWP project making sure to set its type as 'content'
Then in the proper cs file, using DllImport to PInvoke the dll.
There is one more thing: You need to make sure your Python dll is not using prohibited APIs in WinRT. You can check this by using /ZW compile option for the dll.
I want to use gsdll32.dll from Metro Style App c#. I load dll as follow:
[DllImport("gsdll32.dll", EntryPoint = "gsapi_delete_instance")]
private static extern void gsapi_delete_instance(IntPtr instance);
[DllImport("gsdll32.dll", EntryPoint = "gsapi_revision")]
private static extern int gsapi_revision(ref GS_Revision pGSRevisionInfo, int intLen);
[DllImport("gsdll32.dll", EntryPoint = "gsapi_set_stdio")]
private static extern int gsapi_set_stdio(IntPtr lngGSInstance, StdioCallBack gsdll_stdin, StdioCallBack gsdll_stdout, StdioCallBack gsdll_stderr);
But when I try to load dll not found exception occurs. I have already put it in Debug file. But it does work.
I reference from this link.
It is possible, but:
Was gsdll32.dll compiled against the WinRT SDK?
Does gsdll32.dll passes the App certification?
Did you include the dll in your package?
If the answer to any of those questions is "no", then your code will not work.
Build Ghostscript from source (PC version)
Microsoft Environment for WinRT
Ghostscript can be built in the form of a win32 DLL for use within a Windows Runtime application or Windows Runtime component. Building for WinRT requires use of Microsoft Visual Studio 2012. There is a solution file that can be loaded into VS 2012, in the directory winrt
The WinRT application or component should include iapi.h from gs/psi and link with gsdll32metro.lib from gs/debugbin or gs/releasebin. Also any app using ghostscript either directly or via a component should add gsdll32metro.dll as "content". This inclusion of the dll is necessary so that it will be packaged with the app. If one wishes to be able to run the debugger on ghostscript then gsdll32metro.pdb should also be added as content.
From the GhostScript 9.21 documentation
Yes, I do realize this question is half a decade old.