Matlab-generated Dll in C - c

I created a dll of a simple function in Matlab using this command:
mcc -t -L C -W lib:testfunctionLib -T link:lib testfunction.m libmmfile.mlib
The simple function looks like:
function y = testfunction(x)
y = x + 10;
end
I need to call the dll via c-code. This is what i'm using to get the result of the computation with the dll-function into a textfile:
#include <windows.h>
#include <stdio.h>
int main()
{
int z = 1;
FILE *Testfile;
typedef int(*BinaryFunction_t) (int);
BinaryFunction_t AddNumbers;
int result;
BOOL fFreeResult;
HINSTANCE hinstLib = LoadLibraryA("testfunctionLib.dll");
if (hinstLib != NULL)
{
AddNumbers = (BinaryFunction_t)GetProcAddress(hinstLib, "testfunction");
if (AddNumbers != NULL)
result = (*AddNumbers) (z);
fFreeResult = FreeLibrary(hinstLib);
Testfile = fopen("Testfile.txt", "a");
fprintf(Testfile, "%i\n", result);
fclose(Testfile);
}
else
{
Testfile = fopen("Testfile.txt", "a");
fprintf(Testfile, "NOT");
fclose(Testfile);
}
}
I always get a 'NOT' in my textfile because the c-code can't extract the function out of the dll. Why doesn't this work? The c-code for getting the dll-function should be ok, i tested it with a dll created within visual studio.

I know that the library failed to load, but i don't receive any error message.. I also tried to build the dll by the Matlab Coder. I get i lot of different files (c,h,etc) and a single dll-file called testfunction. But including this dll is still not working..

Related

how can i search .txt files in a folder in C?

I want to get file extensions without using standart libraries in C. so basically i want to search for .txt files in a folder which includes .png, .txt, .jpg files.
I don't have a certain code to show, although while I was searching I found a code which includes <dirent.h> and everybody was saying this code cannot be done without that library. Can't I do it without that? and also in some websites they were saying <dirent.h> is only a library for Linux. I'm using MacOS.
code was this: How can I get only txt files from directory in c?
error is this:
Member reference base type 'char [1024]' is not a structure or union.
Can you help me?
If it is supposed to work on macOS only, you can use macOS native frameworks instead of standard libraries, like this:
#include "CoreFoundation/CoreFoundation.h"
int main(int argc, const char * argv[]) {
CFStringRef extension = CFStringCreateWithCString(NULL, ".txt", CFStringGetSystemEncoding());
CFStringRef folderURLString = CFStringCreateWithCString(NULL, "file:///Users/mousetail/Downloads/", CFStringGetSystemEncoding());
CFURLRef folderURL = CFURLCreateWithString(NULL, folderURLString, NULL);
CFURLEnumeratorRef enumerator = CFURLEnumeratorCreateForDirectoryURL(NULL, folderURL, kCFURLEnumeratorDefaultBehavior, NULL);
while (true) {
CFURLRef fileURL = NULL;
CFURLEnumeratorResult enumeratorResult = CFURLEnumeratorGetNextURL(enumerator, &fileURL, NULL);
if (kCFURLEnumeratorSuccess == enumeratorResult) {
CFStringRef fileURLString = CFURLGetString(fileURL);
if (CFStringHasSuffix(fileURLString, extension)) {
CFShow(fileURLString);
}
} else if (kCFURLEnumeratorEnd == enumeratorResult) {
break;
}
}
CFRelease(enumerator);
CFRelease(folderURL);
CFRelease(folderURLString);
CFRelease(extension);
return 0;
}

Use a dynamic library dll in C program

I want to use a dll-file in my C-Code, but are very confused about the syntax.
My Story: I made a simple function in Matlab ( f(x1,x2)=x1*x2 ), with the "Matlab Coder" I translated it to C-Code and generated an exe, I could run it from the terminal with arguments.Now I generated a dll instead of an exe and want to use the dll.
Since now I could not make Code explanations, I googled, make work for me. I look up Syntax in http://en.cppreference.com/w/ but for my surprise there wasn't even an entry for e.g. GetProcAddress or LoadLirbary.
Here is the C-Code in which I would like to use the dll:
#include <stdio.h>
#include <stdlib.h>
/*
* In my dream I would load the dll function here
* with something like Load(mytimes4.dll)
*/
int main(int argc, char *argv[]) {
double x1,x2,myresult;
//Load Arguments from Terminal
sscanf(argv[1], "%lf", &x1);
sscanf(argv[2], "%lf", &x2);
// Use and print the function from mytimes4.dll
myresult = mytimes4(x1,x2);
printf("%3.2f\n",myresult);
return 0;
}
After generating the dll, Matlab gave me the following folder:
"dll-folder" produced by Matlab
Can someone give me a most simple but complete Code that would work with my example? What files are needed (maybe .def or .exp)? Also for Explanations of the lines involved using the dll I would be gratefull. Or if not, you maybe have some background knowledge that makes the complex syntax reasonable.Thanks in advance!
System information: Windows 7 Pro 64, Matlab 64 2016b, gcc cygwin 64, eclipse ide.
With the link of thurizas I could solve my problem.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686944(v=vs.85).aspx
I copied the code from the side. Below you can see the code with additional comments of mine and with ,in my opinion, more clearly naming. Thus it is probably easier to use for beginners as I am.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
/*Declaration of the function,contained in dll, as pointer with the arbitrary pointer name
"*MYFUNCTIONPOINTER" (not sure if it has to be in big letters).
In my case the function means simply f(x1,x2) = x1*x2 and is thus as double declared*/
typedef double (*MYFUNCTIONPOINTER)(double, double);
int main() {
HINSTANCE hinstLib;
//"myfunction" is the arbitrary name the function will be called later
MYFUNCTIONPOINTER myfunction;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
//Tell the dll file
hinstLib = LoadLibrary(TEXT("mypersonal.dll"));
if (hinstLib != NULL)
{
/* At this line "myfunction" gets its definition from "MYFUNCTIONPOINTER"
and can be used as any other function.The relevant function in the dll has
to be told here.*/
myfunction = (MYFUNCTIONPOINTER) GetProcAddress(hinstLib, "mydllfunction");
// If the function address is valid, call the function.
if (NULL != myfunction)
{
fRunTimeLinkSuccess = TRUE;
// The function can be used.
double myoutput;
myoutput = myfunction(5,7);
printf("%f\n",myoutput);
getchar();
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}

Running a terminal command from a C program in OS X

I'm trying to use plotutils to generate a plot from binary data. First, I wrote a C program to export some sample binary data. Then, when I execute the following command in terminal, the plot gets generated as expected.
graph -T png -I d <'/Users/username/Documents/Restofpath/PlotutilsDataGen/testData'> '/Users/username/Documents/Restofpath/PlotutilsDataGen/testPlot.png'
But I want to combine this command with the C code that generates the binary data file so that once the code is executed, the plot is automatically exported. I tried two approaches: (i) using popen() which I suspect I'm doing incorrectly, and (ii) using system() which I thought should work, but doesn't. My entire code is as follows (I've listed both approaches together in the code by I naturally tried them individually):
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int numSamples = 1024;
double outputVec[2*numSamples];
char outputPath[200] = "/Users/username/Documents/Restofpath/PlotutilsDataGen/testData";
char plotcommand[400] = "graph -T png -I d <'/Users/username/Documents/Restofpath/PlotutilsDataGen/testData'> '/Users/username/Documents/Restofpath/PlotutilsDataGen/testPlot.png'";
FILE *fp, *p;
// Compute sample functions to export
for(int ii = 0; ii < (2*numSamples); ii = ii + 2)
{
outputVec[ii] = (double)ii/2;
outputVec[ii+1] = (double)(ii*2);
}
// Export as binary data file for plotutils to use for plotting
fp = fopen(outputPath, "wb");
fwrite(outputVec, sizeof(double), 2*numSamples, fp);
fclose(fp);
// Option 1
p = popen(plotcommand, "w");
pclose(p);
// Option 2
system(plotcommand);
return 0;
}
Any ideas as to what I'm doing wrong or how I might get this to work? Thanks.

Importing C functions in System Verilog with file-type Argument

I am trying to import a C function into a System verilog test bench. The code for the C function is as shown below. I want to pass files as arguments. The function basically reads from one file and writes to another.
int readmem(int z, FILE *file1, FILE *file2) {
char data;
int x;
int i;
for(i = 0; i<z;i ++) {
data = fgetc(file1);
x = data;
fputc(x,file2);
}
return 0;
}
Kindly advise me on how I could call this function in a System verilog test bench.
You cannot pass file descriptors between SystemVerilog and C via the DPI, so I don't think it's possible to import the function directly as-is.
If all you really need to do is get the functionality in SystemVerilog, it will be easier to just port it to SystemVerilog rather than trying to import it via the DPI.
Something like this should work (not tested!):
function int readmem(int z, int file1, int file2);
reg[8:0] data;
for (int i = 0; i < z; i++) begin
data = $fgetc(file1); // Really should break out of the loop if data == EOF ('h1FF)
$fwrite(file2, "%c", data[7:0]);
end
return 0;
endfunction
Then from somewhere else:
int file1 = $fopen("input_file", "r");
int file2 = $fopen("output_file", "w");
readmem(10, file1, file2)
The reason data is declared as 9 bits is to capture an EOF if the end of file is reached. Your original function could run past the end of file1 since you are not checking for EOF.
SystemVerilog includes DPI (Direct Programming Interface) which lets your SystemVerilog call C functions and can even let your C call SystemVerilog tasks/functions. Check out IEEE std 1800-2009 Section 35 and Annex H & I. There are limitations with data types so check out Annex H.7.4 that for basic SV/C type mapping.
To call C functions in SystemVerilog, simply import it into the desired scope (e.g. module or package)
import "DPI-C" context function C_function_name(/* args */);
To call SystemVerilog from C requires one extra step.
In SV :
export "DPI-C" function SV_function_name; /*no args */
In C :
extern return_type SV_function_name( /* args */);
Depending on your simulator you may need to compile the C code first and reference the object file, or just include the source file in your file list. You make need to add options to your simulator to, so check the manual.
Here are some resources that can help you get started:
http://en.wikipedia.org/wiki/SystemVerilog_DPI
http://www.doulos.com/knowhow/sysverilog/tutorial/dpi/
http://www.asic-world.com/examples/systemverilog/dpi.html
Revision:
Use a translate wrapper since FILE does does not translate across DPI. C's const char* maps to SystemVerilog's string.
C:
#include <stdlib.h>
#include <stdio.h>
// include for DPI
#include "svdpi.h"
// wrapper
int C2SV_readmem(int z, const char *filename1, const char *filename2) {
FILE *file1;
FILE *file2;
int rtn;
file1 = fopen(filename1, "r");
file2 = fopen(filename2, "w");
if (file1 == NULL) {
printf("failed to open '%s' for read\n", filename1);
return 1;
}
if (file2 == NULL) {
printf("failed to open '%s' for write\n", filename2);
return 1;
}
return readmem(z, file1, file2); // call original readmem function
}
/* ... */
SystemVerilog:
module test;
import "DPI-C" context function int C2SV_readmem(input int z, input string filename1, input string filename2);
int value;
initial begin
value = C2SV_readmem( 25, "FileIn.txt", "FileOut.txt");
end
endmodule

How do I access functions from libsndfile-1.dll in MSVC?

I'm having trouble getting libsndfile-1.dll to work in my MSVC project. I can load the library and retrieve the version string from the dll by calling sf_command() from my code. However, I can't seem to get sf__open() to return a SNDFILE pointer.
I've also noticed that I can't get fopen() to return a FILE pointer either (maybe this is related, I think sf_open() uses fopen()!?).
I'm pretty new to MSVC, C/C++ and windows in general so I'm probably missing something really obvious.
My main.cpp looks like this:
#include <windows.h>
#include <stdio.h>
#include "sndfile.hh"
// create some function pointers to point to the dll function addresses
// I'm winging this a bit. hopefully it's right!? seems to work!
typedef int (*SF_COMMAND)(SNDFILE*, int, void*, int);
typedef SNDFILE* (*SF_OPEN)(const char*, int, SF_INFO*);
int main()
{
// dll handle
HINSTANCE hDLL = NULL;
// create some vars to store the dll funcs in
SF_COMMAND sf_command;
SF_OPEN sf_open;
// load the dll
hDLL = LoadLibrary(L"libsndfile-1.dll");
// check the dll loaded
if( NULL == hDLL )
{
printf("Error, Could not load library \n");
return 1;
}
// get the dll funcs
sf_command = (SF_COMMAND)GetProcAddress(hDLL, "sf_command");
sf_open = (SF_OPEN)GetProcAddress(hDLL, "sf_open");
// check we got the funcs
if(!(sf_command && sf_open)){
printf("Error exporting dll functions \n");
return 2;
}
// all good so far!
// try the first function
char* version_string[sizeof(char*)*4];
int res = sf_command(NULL, SFC_GET_LIB_VERSION, &version_string, sizeof(version_string));
if(res){
// all good!
printf("Version: %s \n", version_string);
}
// now try and create a SNDFILE pointer
SF_INFO info;
SNDFILE* sfp = sf_open("c:\\Godspeed.aif", SFM_READ, &info);
if(sfp){
printf("Hurray! successfully opened the SNDFILE!! \n");
}else{
printf("Doh! couldn't open the SNDFILE!! \n");
// Grr!!
return 3;
}
return 0;
}
The project builds and exits with code 3 (couldn't open the file! (I'm pretty sure the file is there!!)).
When I run the exe the output is:
Version: libsndfile-1.0.17
Doh! couldn't open the SNDFILE
Does anyone have any suggestions as to where I'm going wrong?
Many thanks,
Josh.
Hmm, I really should learn not to post to forums late at night!
I had another attempt this morning and had the file open within minutes.
I was getting my paths all wrong (not used to these weird windows paths)!
I tried using a relative path and bingo!
Hope that helps someone!

Resources