libharu memory allocation failed while loading image - c

I have some C code trying to use libharu. Although I can use every function of this library (even UTF8) I can hardly draw images. Here is some very basic code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <setjmp.h>
#include "hpdf.h"
jmp_buf env;
#ifdef HPDF_DLL
void __stdcall
#else
void
#endif
error_handler (HPDF_STATUS error_no,
HPDF_STATUS detail_no,
void *user_data)
{
printf ("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no,
(HPDF_UINT)detail_no);
longjmp(env, 1);
}
int main (int argc, char **argv)
{
HPDF_Doc pdf;
HPDF_Font font;
HPDF_Page page;
char fname[256];
HPDF_Image image;
strcpy (fname, argv[0]);
strcat (fname, ".pdf");
pdf = HPDF_New (error_handler, NULL);
if (!pdf) {
printf ("error: cannot create PdfDoc object\n");
return 1;
}
/* error-handler */
if (setjmp(env)) {
HPDF_Free (pdf);
return 1;
}
font = HPDF_GetFont (pdf, "Helvetica", NULL);
page = HPDF_AddPage (pdf);
HPDF_Page_SetWidth (page, 550);
HPDF_Page_SetHeight (page, 500);
image = HPDF_LoadPngImageFromFile (pdf, "img.png");
HPDF_SaveToFile (pdf, fname);
HPDF_Free (pdf);
return 0;
}
When I compile this I have ERROR: error_no=1015, detail_no=0. I have found a similar post in stackoverflow: this. However although original poster said the problem is solved it hardly helped mine. I moved img.png to a folder and recompiled the file. Changed the code that says /home/name/path/to/img.png which is the direct path to image. Nothing works. I "always" have the same error, but when I change the name of file I have ERROR: error_no=1017, detail_no=2 which basicly means program cannot find image (according to reference of libharu) So I deduce that program finds img.png; but, it's strange but, cannot allocate the necessary memory. Which is weird because I cannot see any reason for this program not to allocate memory. I have every kind of permission.
I am using GCC 4.7.2 under Ubuntu Quantal Quetzal and libharu 2.3.0 RC2. Thank you for your help.

Hello Equalities of polynomials .
I also encountered the same problem when i integrated the haru sdk in my macOS environment.
The error_handler returned ERROR: error_no=1017, detail_no=2,and then i checked the official document for haru at http://libharu.sourceforge.net/error_handling.html query 0x1017 indicates that the file failed to open, so i suspect that the second parameter of the HPDF_LoadPngImageFromFile method needs to pass an exact png image file path, so after I modified it, the problem was solved, and I hope to help you.
code ad follow:
char filename1[255];
strcpy(filename1, "/Users/xx/Downloads/lusaceg.com.png");
image = HPDF_LoadPngImageFromFile (pdf, filename1);
Faithfully yours.

Related

Problem getting full version number for Windows 10 with GetFileVersionInfo and VerQueryValue

I want to get the full version number for Windows, just like CMD does:
I ended up with this MS doc that says:
To obtain the full version number for the operating system, call the
GetFileVersionInfo function on one of the system DLLs, such as
Kernel32.dll, then call VerQueryValue to obtain the
\StringFileInfo\\ProductVersion subblock of the file version
information.
So I tried to use those functions with this code:
#include <Windows.h>
#include <wchar.h>
#pragma comment(lib, "Mincore.lib")
int wmain(int argc, wchar_t* argv[])
{
// GetFileVersionInfoW
LPCWSTR fileName = L"C:\\Windows\\System32\\kernel32.dll";
DWORD fileInfoSize;
fileInfoSize = GetFileVersionInfoSizeW(fileName, NULL);
if (fileInfoSize == 0)
{
fwprintf(stderr, L"\nError code: %u\n", GetLastError());
return;
}
// GetFileVersionInfoW
VOID* pFileVerInfo = malloc(fileInfoSize);
if (pFileVerInfo == NULL)
{
fwprintf(stderr, L"Failed allocating!\n");
return;
}
if (!GetFileVersionInfoW(fileName, 0, fileInfoSize, pFileVerInfo))
{
fwprintf(stderr, L"Error code: %u\n", GetLastError());
free(pFileVerInfo);
return;
}
// VerQueryValueW
LPCWSTR subBlock = L"\\StringFileInfo\\\\ProductVersion";
VS_FIXEDFILEINFO * pFileInfo;
UINT pLen = 0;
if (!VerQueryValueW(pFileVerInfo, subBlock, (LPVOID*)& pFileInfo, &pLen))
{
fwprintf(stderr, L"Error code: %u\n", GetLastError());
return;
}
return 0;
}
However, the VerQueryValueW function fails with code 1813 and I have no idea why. I also have no idea how I can show the full version after calling the function.
Can you help me?
L"\\StringFileInfo\\\\ProductVersion" is not correct. There must be a Language ID in the middle. On my Windows 10 installation, a working string is: L"\\StringFileInfo\\040904B0\\ProductVersion". But maybe this would differ on other systems.
As suggested by Jonathan Potter in comments, you could find the ID by querying \\VarFileInfo\\Translation.
Simpler options to achieve the goal include:
Query VS_FIXEDFILEINFO instead of StringFileInfo
Read the OS version from the Windows API instead of querying a random DLL.

winapi create shortcut failed

I want to create shortcut of a file. I found this Microsoft page that describe how to write this, and I copy that in my code to use.
But I have some problems, first it had the following error: "CoInitialize has not been called." I add this CoInitialize(nullptr); to solve the error, but I have error yet.
when I debug it, it has "Information not available, no symbols loaded for windows.storage.dll" error on this line:
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
and after execution when I see the destination path, it creates a shortcut with the name but i can't open it, and it hasn't any content.
What wrong with this?
Does the error make this problem?
I'm using VS 2012.
Code Edited:
// #include "stdafx.h"
#include "windows.h"
#include "shobjidl.h"
#include <iostream>
#include <shlwapi.h>
#include "objbase.h"
#include "objidl.h"
#include "shlguid.h"
HRESULT CreateLink(LPCWSTR, LPCWSTR, LPCWSTR);
void wmain(int argc, wchar_t* argv[ ], wchar_t* envp[ ])
{
WCHAR lpwSource[MAX_PATH] = {0};
lstrcpyW(lpwSource, (LPCWSTR)argv[1]);
WCHAR lpwDest[MAX_PATH] = {0};
lstrcpyW(lpwDest, (LPCWSTR)argv[2]);
HRESULT hResult = 0;
hResult = CreateLink(lpwSource, lpwDest, NULL);
if (hResult == S_OK) {
printf("Shortcut was created successfully.\n");
} else {
printf("Shortcut creation failed.\n");
}
getchar();
}
HRESULT CreateLink(LPCWSTR lpszPathObj, LPCWSTR lpszPathLink, LPCWSTR lpszDesc)
{
HRESULT hres = 0;
IShellLink* psl;
HRESULT hCoInit = 0;
hCoInit = CoInitialize(nullptr);
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called.
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hres)) {
IPersistFile* ppf;
// Set the path to the shortcut target and add the description.
psl->SetPath(lpszPathObj);
psl->SetDescription(lpszDesc);
// Query IShellLink for the IPersistFile interface, used for saving the
// shortcut in persistent storage.
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
if (SUCCEEDED(hres)) {
// Save the link by calling IPersistFile::Save.
hres = ppf->Save(lpszPathLink, TRUE);
ppf->Release();
}
psl->Release();
}
return hres;
}
As I specified in my comment, I've built the code (previous version (Question VERSION #2.) from the one at answer time - which BTW was containing some string conversions that would have most likely failed on non English locales) with VStudio 2013 and ran it on my Win 10 (English) machine. It created a valid shortcut.
So, there was nothing wrong with the code (in the sense that it wouldn't work). The problem was that the output file was also having the .png extension, and when opening it, Win would attempt to use the default image viewer / editor, which would treat the file as PNG (based on its extension). That is obviously wrong, as .lnk files have their own format (as I briefly explained in [SO]: What is the internal structure of a Windows shortcut? (#CristiFati's answer)).
The solution was to properly name the shortcut (let it have the .lnk extension).
Some additional (non critical) notes about the code (current state):
No need for C++ (11) features (nullptr (also check next bullet)):
HRESULT hCoInit = CoInitialize(NULL);
Reorganize the #includes. Use the following list:
#include <windows.h>
#include <shobjidl.h>
#include <shlguid.h>
#include <stdio.h>

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;
}

Ruby C extension rb_str_new2 seems to return false

I cannot post my actual code due to work copyright, so I will try to show my problem with simple example code.
I have a C extension whose simplified version looks like:
#include <ruby.h>
#include <termios.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
VALUE test(VALUE self, VALUE string);
void Init_module_name() {
module_name = rb_define_module("Modulename");
c_modulename = rb_define_class_under(modulename, "Class", rb_cObject);
rb_define_method(c_modulename, "test", test, 1);
e_ModuleNameError = rb_define_class_under(modulename, "Error", rb_eStandardError);
}
VALUE test(VALUE self, VALUE string) {
char *c_string = StringValueCStr(string);
int fd = open(c_string, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd == -1) {
rb_raise(e_ModuleNameError, "Failed to open file");
}
if (!isatty(fd)) {
rb_raise(e_ModuleNameError, "File is not a tty");
}
struct termios config;
int termios_ret = init_termios(config, fd)
if (termios_ret != OK) { // OK defined by enum in modulename's header
close(fd);
rb_raise(e_ModuleNameError, "Termios init failed.");
}
int success = write(fd, "I'm a string", str_length);
if (success < str_length) {
close(fd);
rb_raise(e_ModuleNameError, "Failed to write to file.");
}
close(fd);
return rb_str_new2("Success");
}
Then, the ruby code that requires this looks like:
require 'modulename'
class ModuleName
attr_acessor :file
def initialize(file)
#file = file
#object = Modulename::Class.new
end
def test
#object.test #file
end
end
Which is then called in my production project like:
require "modulename_ruby_file"
x = ModuleName "/dev/pts/1"
x.test
Here is the interesting thing. When I run this code in production, the return value from x.test above is false (As in literally the value false, not a string). Also, the write to the file never happens. However, if I do it in some simplified test code it returns the string "Success" just like expected and the write is indeed completed.
Does anyone know of any situation that would cause this function not to execute the write, and return false? I already tried putting a rescue around it in case it was throwing one of the rb_raises, but it doesn't appear to be.
Me and 3 other members of my team have looked at this all afternoon and have not found an answer.
Finally figured this out, and it was very similar to what #NeilSlater was saying in the comments on the question.
We added a TON of debugging to the C code and had it write to a log file, and figured out that the C function (test in my example) was literally never being called. So, we looked at the symbol table for the .so and the assembly code gcc was generating and both looked fine. Finally we just said, "Let's change the name of the function and see if that helps" and... it worked. The actual function was named logout, and changing it to project_name_logout worked, so apparently there was some kind of namespace collision. So, much like #NeilSlater said, it had something to do with the environment!
So, for anyone else finding this on google: Add a "namespace" to your C code by prefixing all functions with your project name and you should be able to avoid this issue. [One of the other members mentioned, after the fact, that this was a good practice in C anyway.]
Note: We did not take the time to track down what was colliding with logout.

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