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
Related
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;
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!
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?
Thanks In advance for you time and Help.
Goal: I am trying to use my C# library within a C++ project
What I did:
Created a simple .dll file with my C# project. named: ClassLibrary1.dll
Created a C++ console application named: CppClr (Common Language RunTime Support Changed to: /clr)
Copied ClassLibrary1.dll to the root off CppClr project
Following is my ClassLibrary1(C#) code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibrary1
{
public class Class1
{
public static void output()
{
String mystr;
mystr = "Helloo World"; // create a new string
Console.WriteLine(mystr);
Console.WriteLine("From C++ Managed Code!");
Console.ReadLine();
}
}
}
The Following is my C++/CLI code:
#include "CppClr.h"
#using <ClassLibrary1.dll>
int main()
{
ClassLibrary1::Class1::output();
}
Problem: The error I get when I run my C++/CLI code :
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module.Additional information: Could not load file or assembly 'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Your problem is simply an issue of your C++ executable not being able find/load the C# DLL at runtime.
There are a few different places that the .NET runtime looks to load assemblies. The simplest of these is from the same directory that your compiled application is running from. It is not enough to have ClassLibrary1.dll in the root of your C++ project - it needs to be in same directory that your project is running from.
As a quick and dirty test, you should be able to verify this by copying ClassLibrary1.dll into the C++ project's output directory. If you're running in the Debug configuration, this will probably be something like C:\Projects\CppClr\Debug\ or wherever your C++ project is. Verify that this is the directory that contains the compiled CppClr.exe file. Once you copy the DLL here and run your project, the runtime should be able to find the DLL and all should be good.
However, this could be kind of a pain if you're frequently updating your C# project, since you'll continually need to copy it to the C++ output folder every time something changes. The solution to this is to add a reference in the C++ project to your C# library.
In Visual Studio, open up your C++ project. From the solution explorer, right-click on references and select Add reference... Next, click on the Browse... button at the bottom of the dialog and browse to the location of ClassLibrary1.dll on your disk. Click on Add and then OK.
Now, whenever you build the C++ project, it will copy the ClassLibrary1.dll assembly into the project's output folder. You should also be able to remove the #using <ClassLibrary1.dll> directive from the top of your C++ file, since adding the DLL as a project reference should perform the same function.
The msdn link shared by Chad is of the case when you want to add a dll created from C++ project.
What you need to do is to create a strong name for your C# library.
To create a strong name for your class library, type the following command at the Visual Studio .NET command prompt:
sn.exe -k MyKeyFile.SNK
Copy the MyKeyFile.SNK file to your project folder.
Double-click the AssemblyInfo.cs file to open the file in Solution Explorer.
Replace the following lines of code in the AssemblyInfo.cs file
[assembly: ComVisible(false)]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
with
[assembly: ComVisible(true)]
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("..\\..\\MyKeyFile.SNK")]
Press CTRL+SHIFT+B to generate the managed DLL.
Now register the managed DLL for use with COM or with Native C++
Call the Managed DLL from Native C++ Code or using it.
The link here is close to what the OP is trying to do.
https://support.microsoft.com/en-us/kb/828736
I was able to solve this problem by specifying the absolute path of the dll file.
before:
#using "ClassLibrary1.dll"
after:
#using "C:\user\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll"
if this works for you, you need to go to Properties -> C/C++ -> General -> "Resolve #using References" and add the path here. then you can use #using "ClassLibrary1.dll" again in your could without the complete path.
Answer was found here
I want to use C# to call c++ dll file to get data.
In C++,
extern "C" int _DLLExport Process_Read( char **msg );
In C#,
[DllImport( "ProcessExport" )]
public static extern int Process_Read( ref string msg );
=================
string msg;
int msg_len = 0;
msg_len = Process_Read( ref msg );
=================
How could I show the msg data?
Thank you.
DllImport can only be used to import C functions, not C++ class methods (even if they are static).
If its a c++ com object if you register it with regsvr32 you can add a reference to the dll in visual studio com references tab and usually visual studio creates an dll (I think its called a runtime callable wrapper) which you can see is created with the nameoflibrary.interop.dll. So MyExecRefsDll.dll if were a com object would become MyExexRefs.Interop.dll. But when you add the reference visual studio usually does this for you automatically in managed code. If you create a c++ dll as a com object by using atl template in c++ it is easier to access from dotnet (Iam referencing unmanaged c++ code from a dll which references another dll file (No code copied from the second dll I just reference the tlb, lib, the dll file, and visual studio does everything else.
Take a look at this tutorial it makes the process as clear as a crystal ball:
http://www.codeproject.com/Articles/505791/A-Beginner-Tutorial-for-Writing-Simple-COM-ATL-DLL?q=creating+an+atl+dll+c%2b%2b
Just remember to find the tlb and lib (usually in the folder where the other dll is created after compiling. ) and reference them by right clicking in solution explorer and add->existing item for the second dll referenced from the main dll. The tlb and lib allow you to call functions from the dll (always copy new versions of them into your projects folder everytime you update the code to the second dll).